<?php
// The source code packaged with this file is Free Software, Copyright (C) 2005 by
// Ricardo Galli <gallir at uib dot es>.
// It's licensed under the AFFERO GENERAL PUBLIC LICENSE unless stated otherwise.
// You can get copies of the licenses here:
// 		http://www.affero.org/oagpl.html
// AFFERO GENERAL PUBLIC LICENSE is also included in the file called "COPYING".

class Link {
	var $id = 0;
	var $author = -1;
	var $username = false;
	var $randkey = 0;
	var $karma = 1;
	var $valid = true;
	var $date = false;
	var $published_date = 0;
	var $modified = 0;
	var $url = true;
	var $url_title = '';
	var $encoding = false;
	var $status = 'discard';
	var $type = '';
	var $category = 0;
	var $votes = 0;
	var $comments = 0;
	var $reports = 0;
	var $title = '';
	var $title_url = '';
	var $tags = '';
	var $content = '';
	var $html = true;
	var $trackback = false;
	var $read = true;
	var $fullread = true;
	var $voted = false;
	var $lastcomment_userid = 0;
	var $lastcomment_username = '';
	var $lastcomment_usernames = '';
	var $lastcomment_id = 0;
	var $lastcomment_time = '';
	var $lastcomment_content = '';
	var $lastthing_list = '';
	var $link_field1 = '';
	var $link_field2 = '';
	var $link_field3 = '';
	var $link_field4 = '';
	var $link_field5 = '';
	var $link_field6 = '';
	var $link_field7 = '';
	var $link_field8 = '';
	var $link_field9 = '';
	var $link_field10 = '';
	var $link_field11 = '';
	var $link_field12 = '';
	var $link_field13 = '';
	var $link_field14 = '';
	var $link_field15 = '';
	var $current_user_votes = 0;
	var $current_user_reports = 0;
	var $debug = false;
	var $check_saved = true; // check to see if the user has 'saved' this link. sidebarstories doesn't need to check (so don't waste time on it)
	var $get_author_info = true; // get information about the link_author. sidebarstories doesn't need this information (so don't waste time on it)
	var $check_friends = true; // see if the author is a friend of the logged in user.  sidebarstories doesn't need this information (so don't waste time on it)

	function get($url) {
		$url=trim($url);

		if(CHECK_SPAM && $this->check_spam($url)){
			$this->valid = false;
			return;
		}
		if(Validate_URL != false){
			if($url != 'http://' && $url != ''){
				$r = new HTTPRequest($url);
				$xxx = $r->DownloadToString();
			} else {
				$xxx = '';
			}
		}else{
			$xxx = "";
			$this->valid = true;
			$this->url=$url;
			return;
		}


		if(!($this->html = $xxx)) {
			return;
		}

		if($xxx == "BADURL") {
			$this->valid = false; return;
		}
		
		$this->valid = true;
		$this->url=$url;
		if(preg_match('/charset=([a-zA-Z0-9-_]+)/i', $this->html, $matches)) {
			$this->encoding=trim($matches[1]);
			//you need iconv to encode to utf-8
			if(function_exists("iconv"))
			{
				if(strcasecmp($this->encoding, 'utf-8') != 0) {
					//convert the html code into utf-8 whatever encoding it is using
					$this->html=iconv($this->encoding, 'UTF-8//IGNORE', $this->html);
				}
			}
		}
		if(preg_match("'<title>([^<]*?)</title>'", $this->html, $matches)) {
			$this->url_title=trim($matches[1]);
		}
		
		// Detect trackbacks
		if (!empty($_POST['trackback'])) {
			$this->trackback=trim($_POST['trackback']);
		} elseif (preg_match('/trackback:ping="([^"]+)"/i', $this->html, $matches) ||
			preg_match('/trackback:ping +rdf:resource="([^>]+)"/i', $this->html, $matches) ||
			preg_match('/<trackback:ping>([^<>]+)/i', $this->html, $matches)) {
			$this->trackback=trim($matches[1]);
		} elseif (preg_match('/<a[^>]+rel="trackback"[^>]*>/i', $this->html, $matches)) {
			if (preg_match('/href="([^"]+)"/i', $matches[0], $matches2)) {
				$this->trackback=trim($matches2[1]);
			}
		} elseif (preg_match('/<a[^>]+href=[^>]+>trackback<\/a>/i', $this->html, $matches)) {
			if (preg_match('/href="([^"]+)"/i', $matches[0], $matches2)) {
				$this->trackback=trim($matches2[1]);
			}
		}

	}
	function type() {
		if (empty($this->type)) {
			return 'normal';
		}
		return $this->type;
	}

	function store() {
		global $db, $current_user;

		$this->store_basic();
		$link_url = $db->escape($this->url);
		$link_url_title = $db->escape($this->url_title);
		$link_title = $db->escape($this->title);
		$link_title_url = $db->escape($this->title_url);
		if($link_title_url == ""){$link_title_url = makeUrlFriendly($this->title);}
		$link_tags = $db->escape($this->tags);
		$link_content = $db->escape($this->content);
		$link_last_comment = $db->escape($this->lastcomment_id);
		$link_field1 = $db->escape($this->link_field1);
		$link_field2 = $db->escape($this->link_field2);
		$link_field3 = $db->escape($this->link_field3);
		$link_field4 = $db->escape($this->link_field4);
		$link_field5 = $db->escape($this->link_field5);
		$link_field6 = $db->escape($this->link_field6);
		$link_field7 = $db->escape($this->link_field7);
		$link_field8 = $db->escape($this->link_field8);
		$link_field9 = $db->escape($this->link_field9);
		$link_field10 = $db->escape($this->link_field10);
		$link_field11 = $db->escape($this->link_field11);
		$link_field12 = $db->escape($this->link_field12);
		$link_field13 = $db->escape($this->link_field13);
		$link_field14 = $db->escape($this->link_field14);
		$link_field15 = $db->escape($this->link_field15);
		$link_summary = $db->escape($this->link_summary);
		$sql = "UPDATE " . table_links . " set link_summary='$link_summary', link_title_url='$link_title_url', link_url='$link_url', link_url_title='$link_url_title', link_title='$link_title', link_content='$link_content', link_tags='$link_tags', link_field1='$link_field1', link_field2='$link_field2', link_field3='$link_field3', link_field4='$link_field4', link_field5='$link_field5', link_field6='$link_field6', link_field7='$link_field7', link_field8='$link_field8', link_field9='$link_field9', link_field10='$link_field10', link_field11='$link_field11', link_field12='$link_field12', link_field13='$link_field13', link_field14='$link_field14', link_field15='$link_field15', link_last_comment='$link_last_comment' WHERE link_id=$this->id";
		if($this->debug == true){echo '<hr>Store:'. $sql . '<hr>';}
		$db->query($sql);
		
		$pos = strrpos($_SERVER["SCRIPT_NAME"], "/");
		$script_name = substr($_SERVER["SCRIPT_NAME"], $pos + 1, 100);
		$script_name = str_replace(".php", "", $script_name);

	}

	function store_basic() {
		global $db, $current_user;

		if(!$this->date) $this->date=time();
		$link_author = $this->author;
		$link_status = $this->status;
		$link_votes = $this->votes;
		$link_comments = $this->comments;
		$link_reports = $this->reports;
		$link_karma = $this->karma;
		$link_randkey = $this->randkey;
		$link_category = $this->category;
		$link_date = $this->date;
		if($this->published_date == 0){$this->published_date = 943941600;}
		$link_published_date = $this->published_date;
	
		if($this->id===0) {
			$sql = "INSERT INTO " . table_links . " (link_author, link_status, link_randkey, link_category, link_date, link_published_date, link_votes, link_karma, link_title, link_content) VALUES ($link_author, '$link_status', $link_randkey, $link_category, FROM_UNIXTIME($link_date), FROM_UNIXTIME($link_published_date), $link_votes, $link_karma, '', '')";

			if($this->debug == true){echo '<hr>store_basic:Insert:' . $sql . '<hr>';}
			$db->query($sql);
			$this->id = $db->insert_id;
			//die('id: ' . $this->id);
		} else {
		// update
			//$sql = "UPDATE " . table_links . " set `link_reports`=$link_reports, `link_comments`=$link_comments, link_author=$link_author, link_status='$link_status', link_randkey=$link_randkey, link_category=$link_category, link_modified=NULL, link_date=FROM_UNIXTIME($link_date), link_published_date=FROM_UNIXTIME($link_published_date), link_votes=$link_votes, link_karma=$link_karma WHERE link_id=$this->id";
			$sql = "UPDATE " . table_links . " set `link_reports`=$link_reports, `link_comments`=$link_comments, link_author=$link_author, link_status='$link_status', link_randkey=$link_randkey, link_category=$link_category, link_modified=NULL, link_votes=$link_votes, link_karma=$link_karma WHERE link_id=$this->id";
			if($this->debug == true){echo '<hr>store_basic:Update:' . $sql . '<hr>';}
			$db->query($sql);
		}
	}

	function read($usecache = TRUE) {
		global $db, $current_user, $cached_links;
		$id = $this->id;

		// check to see if the link is cached
		// if it is, use it
		// if not, get from mysql and save to cache
		
		if (isset($cached_links[$id]) && $usecache == TRUE) {
			$link = $cached_links[$id];
		} else {
			$link = $db->get_row("SELECT " . table_links . ".* FROM " . table_links . " WHERE link_id = $id");
			$cached_links[$id] = $link;
		}
    
		if($link) {
			if ($link->link_comments > 0) {
				require_once(mnminclude.'comment.php');
				require_once(mnminclude.'user.php');
				if ($link->link_last_comment == 0) {
					$link->link_last_comment = $db->get_var("SELECT MAX(comment_id) FROM " . table_comments . " where comment_link_id = " . $id);
				}
				$comment =  new Comment();
				$comment->id = $link->link_last_comment;
				$comment->read();
				$user = new User();
				$user->id = $comment->author;
				$user->read();
				
				$this->lastcomment_id = $link->link_last_comment;
				$this->lastcomment_time = $comment->date;
				$this->lastcomment_userid = $user->id;
				$this->lastcomment_username = $user->username;
				$this->lastcomment_usernames = $user->names;
				$this->lastcomment_content = $comment->content;
				if(strlen($this->lastcomment_content) > StorySummary_ContentTruncate){ $this->lastcomment_content = substr($this->lastcomment_content, 0, StorySummary_ContentTruncate) . "...";}
			}
			
			$this->author=$link->link_author;
			$this->userid=$link->link_author;
			$this->status=$link->link_status;
			$this->votes=$link->link_votes;
			$this->reports=$link->link_reports;
			$this->comments=$link->link_comments;
			$this->randkey=$link->link_randkey;
			$this->category=$link->link_category;
			$this->url= $link->link_url;
			$this->url= str_replace('&amp;', '&', $link->link_url);  
			$this->url_title=$link->link_url_title;
			$this->title=$link->link_title;
			$this->title_url=$link->link_title_url;
			$this->tags=$link->link_tags;
			$this->content=$link->link_content;
			$date=$link->link_date;
			$this->date=unixtimestamp($date);
			$date=$link->link_published_date;
			$this->published_date=unixtimestamp($date);
			$date=$link->link_modified;
			$this->modified=unixtimestamp($date);
			$this->fullread = $this->read = true;
			$this->link_summary = $link->link_summary;

			$this->link_field1=$link->link_field1;
			$this->link_field2=$link->link_field2;
			$this->link_field3=$link->link_field3;
			$this->link_field4=$link->link_field4;
			$this->link_field5=$link->link_field5;
			$this->link_field6=$link->link_field6;
			$this->link_field7=$link->link_field7;
			$this->link_field8=$link->link_field8;
			$this->link_field9=$link->link_field9;
			$this->link_field10=$link->link_field10;
			$this->link_field11=$link->link_field11;
			$this->link_field12=$link->link_field12;
			$this->link_field13=$link->link_field13;
			$this->link_field14=$link->link_field14;
			$this->link_field15=$link->link_field15;

			return true;
		}
		$this->fullread = $this->read = false;
		return false;
	}

	function read_basic() {
		global $db, $current_user;
		$this->username = false;
		$this->fullread = false;
		$id = $this->id;
		if(($link = $db->get_row("SELECT link_comments, link_author, link_status, link_randkey, link_category, link_date, link_votes, link_karma, link_published_date FROM " . table_links . " WHERE link_id = $id"))) {
			$this->author=$link->link_author;
			$this->votes=$link->link_votes;
			$this->karma=$link->link_karma;
			$this->status=$link->link_status;
			$this->randkey=$link->link_randkey;
			$this->category=$link->link_category;
			$date=$link->link_date;
			$this->date=unixtimestamp($date);
			$date=$link->link_published_date;
			$this->published_date=unixtimestamp($date);
			$this->published_date = $link->link_published_date;
			$this->comments=$link->link_comments;
			$this->read = true;
			return true;
		}
		$this->read = false;
		return false;
	}

	function duplicates($url) {
		global $db;
		$link_url=$db->escape($url);
		$n = $db->get_var("SELECT count(*) FROM " . table_links . " WHERE link_url = '$link_url' AND link_status != 'discard'");
		return $n;
	}
	
	function duplicates_title($title) {
		global $db;
		$link_title=$db->escape($title);
		$n = $db->get_var("SELECT count(*) FROM " . table_links . " WHERE link_title = '$link_title' AND link_status != 'discard'");
		return $n;
	}
	
	function print_summary_doing($doing='', $userid=0, $type='full', $fetch = false) {
		$tplname = '';
		switch ($doing) {
			case 'view_reco_cat1':
				$tplname = '/link_summary_view_reco_cat1.tpl';
				break;
			case 'view_reco_cat2':
				$tplname = '/link_summary_view_reco_cat2.tpl';
				break;
			case 'view_staff':
				$tplname = '/link_summary_view_staff.tpl';
				break;
			case 'view_comments':
				$tplname = '/link_summary_view_comments.tpl';
				break;
			case 'view_hunts':
				$tplname = '/link_summary_view_hunts.tpl';
				break;
			case 'owner_hunt':
				$tplname = '/link_summary_owner_hunt.tpl';
				break;
			case 'view_hunt':
				$tplname = '/link_summary_view_hunt.tpl';
				break;
			default:
				$tplname = '/link_summary.tpl';
				break;
		}
				global $current_user, $globals, $the_template, $smarty;
				include_once('./Smarty.class.php');
		
				$main_smarty = new Smarty;
				$main_smarty->compile_check=false;
				// enable caching at your own risk. this code is still experimental
				//$smarty->cache = true;
				$main_smarty->cache_lifetime = 120;

				$main_smarty->cache_dir = "templates_c/";
				$main_smarty->compile_dir = "templates_c/";
				$main_smarty->template_dir = "templates/";
				$main_smarty->config_dir = "";
				$main_smarty->assign('pligg_language', pligg_language);
				$main_smarty->config_load("/languages/lang_" . pligg_language . ".conf");

				if(phpnum() == 4) {
					$main_smarty->force_compile = true;
				}

				$main_smarty = $this->fill_smarty_doing($doing, $userid, $main_smarty, $type);
				
				if ($current_user->authenticated) {
					global $grouplist, $havegroups;
					$main_smarty->assign('grouplist', $grouplist);
					$main_smarty->assign('havegroups', $havegroups);
				}
				
				$main_smarty->assign('use_title_as_link', use_title_as_link);
				$main_smarty->assign('open_in_new_window', open_in_new_window);	
				$main_smarty->assign('use_thumbnails', use_thumbnails);
				$main_smarty->assign('the_template', The_Template);
				include mnminclude.'extra_fields_smarty.php';
				if($fetch == false){
					//$main_smarty->display($the_template . '/link_summary.tpl', 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
					$main_smarty->display($the_template . $tplname, 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
				} else {
					//return $main_smarty->fetch($the_template . '/link_summary.tpl', 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
					return $main_smarty->fetch($the_template . $tplname, 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
				}
	}
	
	function fill_smarty_doing($doing='', $userid=0, $smarty, $type='full'){
		switch ($doing) {
			case 'view_hunts':
				$smarty = $this->deal_hunt_info($smarty);
				$smarty = $this->deal_lastcomment_info($smarty);
				$smarty = $this->deal_link_info($doing='', $userid=0, $smarty, $type='full');
				return $smarty;
				break;
			case 'view_hunt':
				$smarty = $this->deal_hunt_info($smarty);
				$smarty = $this->deal_link_info($doing='', $userid=0, $smarty, $type='full');
				return $smarty;
				break;
			case 'owner_hunt':
				$smarty = $this->deal_ownerhunt_info($smarty);
				$smarty = $this->deal_link_info($doing='', $userid=0, $smarty, $type='full');
				return $smarty;
				break;
			case 'view_reco_cat2':
			case 'view_reco_cat1':
				$smarty = $this->deal_voter_info($doing='', $userid=0, $smarty, $type='full');
				$smarty = $this->deal_link_info($doing='', $userid=0, $smarty, $type='full');
				return $smarty;
				break;
				
			case 'view_staff':
				$smarty = $this->deal_link_info($doing='', $userid=0, $smarty, $type='full');
				return $smarty;
				break;
				
			case 'view_comments':
				static $link_index=0;
				global $current_user, $globals, $the_template, $db;

				$smarty->assign('link_id', $this->id);

				if(!$this->read) return $smarty;

				$url = str_replace('&amp;', '&', htmlspecialchars($this->url));
				$url_short = txt_shorter($url);	

				if($this->url == "http://"){
					$url_short = "http://";
				} else {
					$parsed = parse_url($this->url);
					if(isset($parsed['scheme'])){$url_short = $parsed['scheme'] . "://" . $parsed['host'];}
				}
				$title_short = htmlspecialchars(utf8_wordwrap($this->title, 30, " ", 1));

				$smarty->assign('viewtype', $type);
				$smarty->assign('URL_tagcloud', getmyurl("tagcloud"));
				$smarty->assign('No_URL_Name', No_URL_Name);
				if(track_outgoing == true){
					if(track_outgoing_method == "id"){$smarty->assign('url', getmyurl("out", ($this->id)));}
					if(track_outgoing_method == "title"){$smarty->assign('url', getmyurl("outtitle", urlencode($this->title_url)));}
					if(track_outgoing_method == "url"){$smarty->assign('url', getmyurl("outurl", ($url)));}
				} else {
					$smarty->assign('url', ($url));
				}
				$smarty->assign('enc_url', urlencode($url));
				$smarty->assign('url_short', $url_short);
				$smarty->assign('title_short', $title_short);
				$smarty->assign('title_url', urlencode($this->title_url));
				$smarty->assign('enc_title_short', urlencode($title_short));
				if ($this->title_url == ""){
					$smarty->assign('story_url', getmyurl("story", $this->id)); // internal link to the comments page
				} else {
					$smarty->assign('story_url', getmyurl("storyURL", $this->category_safe_name(), urlencode($this->title_url), $this->id)); // internal link to the comments page
				}

				$smarty->assign('story_edit_url', getmyurl("editlink", $this->id));
				$smarty->assign('story_admin_url', getmyurl("admin_modify", $this->id));
				$smarty->assign('story_comment_count', $this->comments());
				$smarty->assign('story_status', $this->status);
				if($type == "summary"){
					if($this->link_summary == ""){
						$smarty->assign('story_content', $this->truncate_content());
					} else {
						$smarty->assign('story_content', $this->link_summary);
					}
					$smarty->assign('story_desc', $this->content);
				}
				if($type == "full"){
					$smarty->assign('story_content', $this->content);
					$smarty->assign('story_desc', $this->content);
				}
		
				if($this->get_author_info == true){
					$smarty->assign('link_submitter', $this->username());
					$smarty->assign('link_submitter_id', $this->author);
					$smarty->assign('link_submitter_names', $this->usernames());
					$smarty->assign('submitter_profile_url', getmyurl('user', $this->username()));
				}
		
				//$smarty->assign('link_submit_time', $this->date); 		
				$smarty->assign('link_submit_time', get_date($this->date));
				$smarty->assign('link_submit_timeago', txt_time_diff($this->date));
				$smarty->assign('link_published_time', $this->published_date);
				$smarty->assign('link_published_date', get_date($this->published_date));
				$smarty->assign('link_published_timeago', txt_time_diff($this->published_date));
				$smarty->assign('link_category', $this->category_name());
				//assign category id to smarty, so we can use it in the templates. Needed for category colors!
				$smarty->assign('category_id', $this->category);

				global $URLMethod;

				{$catvar = $this->category_safe_name();}

				$smarty->assign('Voting_Method', Voting_Method);
				if(Voting_Method == 2)
				{
					$this->rating = $this->rating($this->id)/2;
					$smarty->assign('link_rating', $this->rating);
					$smarty->assign('link_rating_width', $this->rating * 25);

					$js5link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',10)";
					$smarty->assign('link_shakebox_javascript_vote_5star', $js5link);

					$js4link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',8)";
					$smarty->assign('link_shakebox_javascript_vote_4star', $js4link);

					$js3link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',6)";
					$smarty->assign('link_shakebox_javascript_vote_3star', $js3link);

					$js2link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',4)";
					$smarty->assign('link_shakebox_javascript_vote_2star', $js2link);

					$js1link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',2)";
					$smarty->assign('link_shakebox_javascript_vote_1star', $js1link);

					$this->votecount = $this->countvotes();
					$smarty->assign('vote_count', $this->votecount);
			
					if($this->votes($current_user->user_id) > 0){
						$smarty->assign('star_class', "-noh");
					} else {
						$smarty->assign('star_class', "");
					}
				}

				if($this->status == "published"){$smarty->assign('category_url', getmyurl("maincategory", $catvar));}
				if($this->status == "queued"){$smarty->assign('category_url', getmyurl("queuedcategory", $catvar));}
				if($this->status == "discard"){$smarty->assign('category_url', getmyurl("discardedcategory", $catvar));}

				$smarty->assign('trackback_url', get_trackback($this->id));
				$smarty->assign('user_logged_in', $current_user->user_login);
				$smarty->assign('randmd5', md5($current_user->user_id.$this->randkey));
				$smarty->assign('user_id', $this->author);
				$smarty->assign('current_user_id', $current_user->user_id);

				if(Enable_Extra_Fields){
					$main_smarty = $smarty; include mnminclude.'extra_fields_smarty.php'; $smarty=$main_smarty;
					$smarty->assign('link_field1', $this->link_field1);
					$smarty->assign('link_field2', $this->link_field2);
					$smarty->assign('link_field3', $this->link_field3);
					$smarty->assign('link_field4', $this->link_field4);
					$smarty->assign('link_field5', $this->link_field5);
					$smarty->assign('link_field6', $this->link_field6);
					$smarty->assign('link_field7', $this->link_field7);
					$smarty->assign('link_field8', $this->link_field8);
					$smarty->assign('link_field9', $this->link_field9);
					$smarty->assign('link_field10', $this->link_field10);
					$smarty->assign('link_field11', $this->link_field11);
					$smarty->assign('link_field12', $this->link_field12);
					$smarty->assign('link_field13', $this->link_field13);
					$smarty->assign('link_field14', $this->link_field14);
					$smarty->assign('link_field15', $this->link_field15);
				}

				$smarty->assign('Enable_Recommend', Enable_Recommend);
				$smarty->assign('Recommend_Type', Recommend_Type);
				$smarty->assign('instpath', my_base_url . my_pligg_base . "/");		
				$smarty->assign('UseAvatars', do_we_use_avatars());
				$smarty->assign('Avatar_ImgSrc', get_avatar('large', "", "", "", $this->userid));
				$smarty->assign('Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $this->userid));
				
				//owner info
				$owner_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id = ' . $this->id);
				if ($owner_id) {
					$smarty->assign('link_owner_id',$owner_id);
					$smarty->assign('link_owner_url',my_base_url . my_pligg_base . '/user.php?uid=' . $owner_id);
					$owner_nickname = $db->get_var('SELECT user_names FROM ' . table_users . ' WHERE user_id = ' . $owner_id);
					if ($owner_nickname) {
						$smarty->assign('link_owner_nickname',$owner_nickname);
					}
					else {
						$smarty->assign('link_owner_nickname','');
					}
				}
				else {
					$smarty->assign('link_owner_id',0);
					$smarty->assign('link_owner_url','');
					$smarty->assign('link_owner_nickname','');
				}
				$smarty->assign('Owner_Avatar_ImgSrc', get_avatar('large', "", "", "", $owner_id));
				$smarty->assign('Owner_Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $owner_id));
				
				//comment info
				//voter info
				//$voter_id = $userid;
				//$voter_date = $db->get_var("SELECT vote_date FROM " . table_votes . " WHERE vote_link_id=" . $this->id . " AND vote_user_id=" . $userid);//this time do not use the getdate function
				//$smarty->assign('voter_id', $voter_id);
				//$smarty->assign('voter_date', $voter_date);
				$comments_count = $db->get_var("SELECT COUNT(*) FROM " . table_comments . " WHERE comment_link_id=" . $this->id . " AND comment_user_id=" . $userid);
				$smarty->assign('comments_count', $comments_count);
				if ($comments_count > 0) {	
					$comments = array();
					//$sqlquery = "SELECT * FROM " . table_comments . " WHERE comment_link_id=" . $this->id . " AND comment_user_id=" . $userid;
					$sqlquery = "SELECT * FROM " . table_comments . " WHERE comment_link_id=" . $this->id . " AND comment_user_id=" . $userid . " ORDER BY comment_date ASC";
					$searchsql = mysql_query($sqlquery);
					
					while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($comments, $row);
					foreach ($comments as $key => $val) {
						//die($sqlquery);
						$comments[$key]['currentuservote'] = $db->get_var("SELECT COUNT(*) FROM " . table_votes . " WHERE vote_type='comments' AND vote_link_id=" . $comments[$key]['comment_id'] . " AND vote_user_id=" . $current_user->user_id);
						$comments[$key]['comment_content'] = save_text_to_html($comments[$key]['comment_content']);
					}
					
					$smarty->assign('comments', $comments);
				}
				
				$canIhaveAccess = 0;
				$canIhaveAccess = $canIhaveAccess + checklevel('god');
				$canIhaveAccess = $canIhaveAccess + checklevel('admin');
				if($canIhaveAccess == 1)
					{$smarty->assign('isadmin', 'yes');}

				if($this->check_friends == true){
					// For Friends //
					include_once(mnminclude.'friend.php');
					$friend = new Friend;
					// make sure we're logged in and we didnt submit the link.
					if($current_user->user_id > 0 && $current_user->user_login != $this->username()){
						$friend_md5 = friend_MD5($current_user->user_login, $this->username());
						$smarty->assign('FriendMD5', $friend_md5);
		
						$isfriend = $friend->get_friend_status($this->author);
						if (!$isfriend)	{$friend_text = 'add to';	$friend_url = 'addfriend';}
						else{$friend_text = 'remove from';	$friend_url = 'removefriend';}
		
						$smarty->assign('Friend_Text', $friend_text);				
						$smarty->assign('user_add_remove', getmyurl('user_add_remove', $this->username(), $friend_url));
					}
		
					$smarty->assign('Allow_Friends', Allow_Friends);
					$smarty->assign('Enable_AddTo', Enable_AddTo);
					// --- //
				}
		
				if($this->check_saved == true){
					global $cached_saved_links;
					if(isset($cached_saved_links[$this->id])){
						$smarty->assign('link_mine', $cached_saved_links[$this->id]);
					} else {
						$smarty->assign('link_mine', $db->get_row("SELECT * FROM " . table_saved_links . " WHERE saved_user_id=$current_user->user_id AND saved_link_id=$this->id LIMIT 1;"));
					}
				}
//die('ok');
				$smarty->assign('user_url_saved', getmyurl('user2', $current_user->user_login, 'saved'));
				$smarty->assign('user_url_add_links', getmyurl('user_add_links', $this->id));
				$smarty->assign('user_url_remove_links', getmyurl('user_remove_links', $this->id));
				$smarty->assign('enable_tags', Enable_Tags);
				$smarty->assign('link_shakebox_index', $link_index);
				$smarty->assign('link_shakebox_votes', $this->votes);
		
				$this->get_current_user_votes($current_user->user_id);
		
				$smarty->assign('link_shakebox_currentuser_votes', $this->current_user_votes);
				$smarty->assign('link_shakebox_currentuser_reports', $this->current_user_reports);

				if($this->reports == -1){
					// reporting was added to the svn and some people started using it
					// so in upgrade if someone already has the reports field, we set it to
					// -1. Then when we read() we check if -1. if it still is, update the count
					// from the votes table and store it into the link_reports field so we
					// don't have to look at the votes table again.
		
					$this->reports = $this->count_all_votes("<0");
					$this->store_basic();
					$smarty->assign('link_shakebox_reports', $this->reports);
				}

				$jslink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
				$jsreportlink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',-10)";
				$smarty->assign('link_shakebox_javascript_vote', $jslink);

				$jsunvote = "unvote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
				$smarty->assign('link_shakebox_javascript_unvote', $jsunvote);
		
				$smarty->assign('link_shakebox_javascript_report', $jsreportlink);
				if(!defined('alltagtext')){
					// for pages like index, this ->display was being called for each story
					// which was sometimes 15+ times per page. this way it's just called once
					$smarty->display('blank.tpl'); //this is just to load the lang file so we can pull from it in php
					define('alltagtext', $smarty->get_config_vars('PLIGG_Visual_Tags_All_Tags')); 			
				}
				$alltagtext = alltagtext;
	
				if(Enable_Tags){
					$smarty->assign('tags', $this->tags);
					if (!empty($this->tags)) {
						$tags_words = str_replace(",", ", ", $this->tags);
						$tags_count = substr_count($tags_words, ',');
						if ($tags_count > 1){$tags_words = $tags_words;}

						$tag_array = explode(",", $tags_words);
						$c = count($tag_array);
						$tag_array[$c] = $this->tags;
 						$c++;
 						for($i=0; $i<=$c; $i++)
 						{
 							if(isset($tag_array[$i])){
								if ( $URLMethod == 1 ) { 
						    		$tags_url_array[$i] = my_pligg_base . "/search.php?search=".urlencode(trim($tag_array[$i]))."&amp;tag=true";
								} elseif ( $URLMethod == 2) {
						    		$tags_url_array[$i] = my_pligg_base . "/tag/" . urlencode(trim($tag_array[$i]));
				    			}
				  			}
 						}
 						$tag_array[$c - 1] = $alltagtext;

						$smarty->assign('tag_array', $tag_array);
						$smarty->assign('tags_url_array', $tags_url_array);

						$tags_url = urlencode($this->tags);
						$smarty->assign('tags_count', $tags_count);
						$smarty->assign('tags_words', $tags_words);
						$smarty->assign('tags_url', $tags_url);
					}
				}
		
				$smarty->assign('pagename', pagename);
				$smarty->assign('doing', doing);
				$smarty->assign('my_base_url', my_base_url);
				$smarty->assign('my_pligg_base', my_pligg_base);
				$smarty->assign('Default_Gravatar_Large', Default_Gravatar_Large);
			
				$link_index++;
				$vars = '';
				check_actions('lib_link_summary_fill_smarty', $vars);

				return $smarty;
				
				break;
				
			default:
				
		static $link_index=0;
		global $current_user, $globals, $the_template, $db;

		$smarty->assign('link_id', $this->id);

		if(!$this->read) return $smarty;

		$url = str_replace('&amp;', '&', htmlspecialchars($this->url));
		$url_short = txt_shorter($url);	

		if($this->url == "http://"){
			$url_short = "http://";
		} else {
			$parsed = parse_url($this->url);
			if(isset($parsed['scheme'])){$url_short = $parsed['scheme'] . "://" . $parsed['host'];}
		}
		$title_short = htmlspecialchars(utf8_wordwrap($this->title, 30, " ", 1));

		$smarty->assign('viewtype', $type);
		$smarty->assign('URL_tagcloud', getmyurl("tagcloud"));
		$smarty->assign('No_URL_Name', No_URL_Name);
		if(track_outgoing == true){
			if(track_outgoing_method == "id"){$smarty->assign('url', getmyurl("out", ($this->id)));}
			if(track_outgoing_method == "title"){$smarty->assign('url', getmyurl("outtitle", urlencode($this->title_url)));}
			if(track_outgoing_method == "url"){$smarty->assign('url', getmyurl("outurl", ($url)));}
		} else {
			$smarty->assign('url', ($url));
		}
		$smarty->assign('enc_url', urlencode($url));
		$smarty->assign('url_short', $url_short);
		$smarty->assign('title_short', $title_short);
		$smarty->assign('title_url', urlencode($this->title_url));
		$smarty->assign('enc_title_short', urlencode($title_short));
		if ($this->title_url == ""){
			$smarty->assign('story_url', getmyurl("story", $this->id)); // internal link to the comments page
		} else {
			$smarty->assign('story_url', getmyurl("storyURL", $this->category_safe_name(), urlencode($this->title_url), $this->id)); // internal link to the comments page
		}

		$smarty->assign('story_edit_url', getmyurl("editlink", $this->id));
		$smarty->assign('story_admin_url', getmyurl("admin_modify", $this->id));
		$smarty->assign('story_comment_count', $this->comments());
		$smarty->assign('story_status', $this->status);
		if($type == "summary"){
			if($this->link_summary == ""){
				$smarty->assign('story_content', $this->truncate_content());
			} else {
				$smarty->assign('story_content', $this->link_summary);
			}
			$smarty->assign('story_desc', $this->content);
		}
		if($type == "full"){
			$smarty->assign('story_content', $this->content);
			$smarty->assign('story_desc', $this->content);
		}
		
		if($this->get_author_info == true){
			$smarty->assign('link_submitter', $this->username());
			$smarty->assign('link_submitter_id', $this->author);
			$smarty->assign('link_submitter_names', $this->usernames());
			$smarty->assign('submitter_profile_url', getmyurl('user', $this->username()));
		}
		
		//$smarty->assign('link_submit_time', $this->date); 		
		$smarty->assign('link_submit_time', get_date($this->date));
		$smarty->assign('link_submit_timeago', txt_time_diff($this->date));
		$smarty->assign('link_published_time', $this->published_date);
		$smarty->assign('link_published_date', get_date($this->published_date));
		$smarty->assign('link_published_timeago', txt_time_diff($this->published_date));
		$smarty->assign('link_category', $this->category_name());
		//assign category id to smarty, so we can use it in the templates. Needed for category colors!
		$smarty->assign('category_id', $this->category);

		global $URLMethod;

		{$catvar = $this->category_safe_name();}

		$smarty->assign('Voting_Method', Voting_Method);
		if(Voting_Method == 2)
		{
			$this->rating = $this->rating($this->id)/2;
			$smarty->assign('link_rating', $this->rating);
			$smarty->assign('link_rating_width', $this->rating * 25);

			$js5link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',10)";
			$smarty->assign('link_shakebox_javascript_vote_5star', $js5link);

			$js4link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',8)";
			$smarty->assign('link_shakebox_javascript_vote_4star', $js4link);

			$js3link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',6)";
			$smarty->assign('link_shakebox_javascript_vote_3star', $js3link);

			$js2link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',4)";
			$smarty->assign('link_shakebox_javascript_vote_2star', $js2link);

			$js1link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',2)";
			$smarty->assign('link_shakebox_javascript_vote_1star', $js1link);

			$this->votecount = $this->countvotes();
			$smarty->assign('vote_count', $this->votecount);
			
			if($this->votes($current_user->user_id) > 0){
				$smarty->assign('star_class', "-noh");
			} else {
				$smarty->assign('star_class', "");
			}
		}

		if($this->status == "published"){$smarty->assign('category_url', getmyurl("maincategory", $catvar));}
		if($this->status == "queued"){$smarty->assign('category_url', getmyurl("queuedcategory", $catvar));}
		if($this->status == "discard"){$smarty->assign('category_url', getmyurl("discardedcategory", $catvar));}

		$smarty->assign('trackback_url', get_trackback($this->id));
		$smarty->assign('user_logged_in', $current_user->user_login);
		$smarty->assign('randmd5', md5($current_user->user_id.$this->randkey));
		$smarty->assign('user_id', $this->author);
		$smarty->assign('current_user_id', $current_user->user_id);

		if(Enable_Extra_Fields){
			$main_smarty = $smarty; include mnminclude.'extra_fields_smarty.php'; $smarty=$main_smarty;
			$smarty->assign('link_field1', $this->link_field1);
			$smarty->assign('link_field2', $this->link_field2);
			$smarty->assign('link_field3', $this->link_field3);
			$smarty->assign('link_field4', $this->link_field4);
			$smarty->assign('link_field5', $this->link_field5);
			$smarty->assign('link_field6', $this->link_field6);
			$smarty->assign('link_field7', $this->link_field7);
			$smarty->assign('link_field8', $this->link_field8);
			$smarty->assign('link_field9', $this->link_field9);
			$smarty->assign('link_field10', $this->link_field10);
			$smarty->assign('link_field11', $this->link_field11);
			$smarty->assign('link_field12', $this->link_field12);
			$smarty->assign('link_field13', $this->link_field13);
			$smarty->assign('link_field14', $this->link_field14);
			$smarty->assign('link_field15', $this->link_field15);
		}

		$smarty->assign('Enable_Recommend', Enable_Recommend);
		$smarty->assign('Recommend_Type', Recommend_Type);
		$smarty->assign('instpath', my_base_url . my_pligg_base . "/");		
		$smarty->assign('UseAvatars', do_we_use_avatars());
		$smarty->assign('Avatar_ImgSrc', get_avatar('large', "", "", "", $this->userid));
		$smarty->assign('Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $this->userid));
		$owner_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id = ' . $this->id);
		if ($owner_id) {
			$smarty->assign('link_owner_id',$owner_id);
			$smarty->assign('link_owner_url',my_base_url . my_pligg_base . '/user.php?uid=' . $owner_id);
			$owner_nickname = $db->get_var('SELECT user_names FROM ' . table_users . ' WHERE user_id = ' . $owner_id);
			if ($owner_nickname) {
				$smarty->assign('link_owner_nickname',$owner_nickname);
			}
			else {
				$smarty->assign('link_owner_nickname','');
			}
		}
		else {
			$smarty->assign('link_owner_id',0);
			$smarty->assign('link_owner_url','');
			$smarty->assign('link_owner_nickname','');
		}
		$smarty->assign('Owner_Avatar_ImgSrc', get_avatar('large', "", "", "", $owner_id));
		$smarty->assign('Owner_Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $owner_id));

		$canIhaveAccess = 0;
		$canIhaveAccess = $canIhaveAccess + checklevel('god');
		$canIhaveAccess = $canIhaveAccess + checklevel('admin');
		if($canIhaveAccess == 1)
			{$smarty->assign('isadmin', 'yes');}

		if($this->check_friends == true){
			// For Friends //
				include_once(mnminclude.'friend.php');
				$friend = new Friend;
				// make sure we're logged in and we didnt submit the link.
				if($current_user->user_id > 0 && $current_user->user_login != $this->username()){
					$friend_md5 = friend_MD5($current_user->user_login, $this->username());
					$smarty->assign('FriendMD5', $friend_md5);
		
					$isfriend = $friend->get_friend_status($this->author);
					if (!$isfriend)	{$friend_text = 'add to';	$friend_url = 'addfriend';}
						else{$friend_text = 'remove from';	$friend_url = 'removefriend';}
		
					$smarty->assign('Friend_Text', $friend_text);				
					$smarty->assign('user_add_remove', getmyurl('user_add_remove', $this->username(), $friend_url));
				}
		
				$smarty->assign('Allow_Friends', Allow_Friends);
				$smarty->assign('Enable_AddTo', Enable_AddTo);
			// --- //
		}
		
		if($this->check_saved == true){
			global $cached_saved_links;
			if(isset($cached_saved_links[$this->id])){
				$smarty->assign('link_mine', $cached_saved_links[$this->id]);
			} else {
				$smarty->assign('link_mine', $db->get_row("SELECT * FROM " . table_saved_links . " WHERE saved_user_id=$current_user->user_id AND saved_link_id=$this->id LIMIT 1;"));
			}
		}

		$smarty->assign('user_url_saved', getmyurl('user2', $current_user->user_login, 'saved'));
		$smarty->assign('user_url_add_links', getmyurl('user_add_links', $this->id));
		$smarty->assign('user_url_remove_links', getmyurl('user_remove_links', $this->id));
		$smarty->assign('enable_tags', Enable_Tags);
		$smarty->assign('link_shakebox_index', $link_index);
		$smarty->assign('link_shakebox_votes', $this->votes);
		
		$this->get_current_user_votes($current_user->user_id);
		
		$smarty->assign('link_shakebox_currentuser_votes', $this->current_user_votes);
		$smarty->assign('link_shakebox_currentuser_reports', $this->current_user_reports);

		if($this->reports == -1){
			// reporting was added to the svn and some people started using it
			// so in upgrade if someone already has the reports field, we set it to
			// -1. Then when we read() we check if -1. if it still is, update the count
			// from the votes table and store it into the link_reports field so we
			// don't have to look at the votes table again.
		
			$this->reports = $this->count_all_votes("<0");
			$this->store_basic();
			$smarty->assign('link_shakebox_reports', $this->reports);
		}

		$jslink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$jsreportlink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',-10)";
		$smarty->assign('link_shakebox_javascript_vote', $jslink);

		$jsunvote = "unvote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$smarty->assign('link_shakebox_javascript_unvote', $jsunvote);
		
		$smarty->assign('link_shakebox_javascript_report', $jsreportlink);
		if(!defined('alltagtext')){
			// for pages like index, this ->display was being called for each story
			// which was sometimes 15+ times per page. this way it's just called once
			$smarty->display('blank.tpl'); //this is just to load the lang file so we can pull from it in php
			define('alltagtext', $smarty->get_config_vars('PLIGG_Visual_Tags_All_Tags')); 			
		}
		$alltagtext = alltagtext;
	
		if(Enable_Tags){
			$smarty->assign('tags', $this->tags);
			if (!empty($this->tags)) {
				$tags_words = str_replace(",", ", ", $this->tags);
				$tags_count = substr_count($tags_words, ',');
				if ($tags_count > 1){$tags_words = $tags_words;}

				$tag_array = explode(",", $tags_words);
				$c = count($tag_array);
				$tag_array[$c] = $this->tags;
 				$c++;
 				for($i=0; $i<=$c; $i++)
 				{
 					if(isset($tag_array[$i])){
						if ( $URLMethod == 1 ) { 
						    $tags_url_array[$i] = my_pligg_base . "/search.php?search=".urlencode(trim($tag_array[$i]))."&amp;tag=true";
						} elseif ( $URLMethod == 2) {
						    $tags_url_array[$i] = my_pligg_base . "/tag/" . urlencode(trim($tag_array[$i]));
				    }
				  }
 				}
 				$tag_array[$c - 1] = $alltagtext;

				$smarty->assign('tag_array', $tag_array);
				$smarty->assign('tags_url_array', $tags_url_array);

				$tags_url = urlencode($this->tags);
				$smarty->assign('tags_count', $tags_count);
				$smarty->assign('tags_words', $tags_words);
				$smarty->assign('tags_url', $tags_url);
			}
		}
		
		$smarty->assign('pagename', pagename);
		$smarty->assign('doing', doing);
		$smarty->assign('my_base_url', my_base_url);
		$smarty->assign('my_pligg_base', my_pligg_base);
		$smarty->assign('Default_Gravatar_Large', Default_Gravatar_Large);
			
		$link_index++;
		$vars = '';
		check_actions('lib_link_summary_fill_smarty', $vars);

		return $smarty;
		
		break;
		}
	}
	
	function print_summary($type='full', $fetch = false) {
		global $current_user, $globals, $the_template, $smarty;

		include_once('./Smarty.class.php');
		
		$main_smarty = new Smarty;
		$main_smarty->compile_check=false;
		// enable caching at your own risk. this code is still experimental
		//$smarty->cache = true;
		$main_smarty->cache_lifetime = 120;
		$main_smarty->cache_dir = "templates_c/";
		$main_smarty->compile_dir = "templates_c/";
		$main_smarty->template_dir = "templates/";
		$main_smarty->config_dir = "";
		$main_smarty->assign('pligg_language', pligg_language);
		$main_smarty->config_load("/languages/lang_" . pligg_language . ".conf");

		if(phpnum() == 4) {
			$main_smarty->force_compile = true;
		}

		$main_smarty = $this->fill_smarty($main_smarty, $type);
		
		if ($current_user->authenticated) {
			global $grouplist, $havegroups;
			$main_smarty->assign('grouplist', $grouplist);
			$main_smarty->assign('havegroups', $havegroups);
		}
		
		$main_smarty->assign('use_title_as_link', use_title_as_link);
		$main_smarty->assign('open_in_new_window', open_in_new_window);
		$main_smarty->assign('use_thumbnails', use_thumbnails);
		$main_smarty->assign('the_template', The_Template);

		include mnminclude.'extra_fields_smarty.php';
		if($fetch == false){
			$main_smarty->display($the_template . '/link_summary.tpl', 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
		} else {
			return $main_smarty->fetch($the_template . '/link_summary.tpl', 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
		}
	}
	
	function fill_smarty($smarty, $type='full'){

		static $link_index=0;
		global $current_user, $globals, $the_template, $db;

		$smarty->assign('lastcomment_userid', $this->lastcomment_userid);
		$smarty->assign('lastcomment_username', $this->lastcomment_username);
		$smarty->assign('lastcomment_usernames', $this->lastcomment_usernames);
		$smarty->assign('lastcomment_id', $this->lastcomment_id);
		$smarty->assign('lastcomment_time', get_date($this->lastcomment_time));
		$smarty->assign('lastcomment_content', $this->lastcomment_content);
		$smarty->assign('lastcomment_useravatar', get_avatar("large",'',$this->lastcomment_username,"",$this->lastcomment_userid));
		$smarty->assign('lastcomment_useravatar_huge', get_avatar("huge",'',$this->lastcomment_username,"",$this->lastcomment_userid));
		$smarty->assign('lastcomment_userprofileurl', my_base_url . my_pligg_base . '/user.php?login=' . $this->lastcomment_username);
	
		$smarty->assign('link_id', $this->id);

		if(!$this->read) return $smarty;

		$url = str_replace('&amp;', '&', htmlspecialchars($this->url));
		$url_short = txt_shorter($url);	

		if($this->url == "http://"){
			$url_short = "http://";
		} else {
			$parsed = parse_url($this->url);
			if(isset($parsed['scheme'])){$url_short = $parsed['scheme'] . "://" . $parsed['host'];}
		}
		$title_short = htmlspecialchars(utf8_wordwrap($this->title, 30, " ", 1));

		$smarty->assign('viewtype', $type);
		$smarty->assign('URL_tagcloud', getmyurl("tagcloud"));
		$smarty->assign('No_URL_Name', No_URL_Name);
		if(track_outgoing == true){
			if(track_outgoing_method == "id"){$smarty->assign('url', getmyurl("out", ($this->id)));}
			if(track_outgoing_method == "title"){$smarty->assign('url', getmyurl("outtitle", urlencode($this->title_url)));}
			if(track_outgoing_method == "url"){$smarty->assign('url', getmyurl("outurl", ($url)));}
		} else {
			$smarty->assign('url', ($url));
		}
		$smarty->assign('enc_url', urlencode($url));
		$smarty->assign('url_short', $url_short);
		$smarty->assign('title_short', $title_short);
		$smarty->assign('title_url', urlencode($this->title_url));
		$smarty->assign('enc_title_short', urlencode($title_short));
		if ($this->title_url == ""){
			$smarty->assign('story_url', getmyurl("story", $this->id)); // internal link to the comments page
		} else {
			$smarty->assign('story_url', getmyurl("storyURL", $this->category_safe_name(), urlencode($this->title_url), $this->id)); // internal link to the comments page
		}

		$smarty->assign('story_edit_url', getmyurl("editlink", $this->id));
		$smarty->assign('story_admin_url', getmyurl("admin_modify", $this->id));
		$smarty->assign('story_comment_count', $this->comments());
		$smarty->assign('story_status', $this->status);
		if($type == "summary"){
			if($this->link_summary == ""){
				$smarty->assign('story_content', $this->truncate_content());
			} else {
				$smarty->assign('story_content', $this->link_summary);
			}
			$smarty->assign('story_desc', $this->content);
		}
		if($type == "full"){
			$smarty->assign('story_content', $this->content);
			$smarty->assign('story_desc', $this->content);
		}
		
		if($this->get_author_info == true){
			$smarty->assign('link_submitter', $this->username());
			$smarty->assign('link_submitter_id', $this->author);
			$smarty->assign('link_submitter_names', $this->usernames());
			$smarty->assign('submitter_profile_url', getmyurl('user', $this->username()));
		}
		
		//$smarty->assign('link_submit_time', $this->date);
		$smarty->assign('link_submit_time', get_date($this->date));
		$smarty->assign('link_submit_timeago', txt_time_diff($this->date));
		$smarty->assign('link_published_time', $this->published_date);
		$smarty->assign('link_published_date', get_date($this->published_date));
		$smarty->assign('link_published_timeago', txt_time_diff($this->published_date));
		$smarty->assign('link_category', $this->category_name());
		//assign category id to smarty, so we can use it in the templates. Needed for category colors!
		$smarty->assign('category_id', $this->category);

		global $URLMethod;

		{$catvar = $this->category_safe_name();}

		$smarty->assign('Voting_Method', Voting_Method);
		if(Voting_Method == 2)
		{
			$this->rating = $this->rating($this->id)/2;
			$smarty->assign('link_rating', $this->rating);
			$smarty->assign('link_rating_width', $this->rating * 25);

			$js5link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',10)";
			$smarty->assign('link_shakebox_javascript_vote_5star', $js5link);

			$js4link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',8)";
			$smarty->assign('link_shakebox_javascript_vote_4star', $js4link);

			$js3link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',6)";
			$smarty->assign('link_shakebox_javascript_vote_3star', $js3link);

			$js2link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',4)";
			$smarty->assign('link_shakebox_javascript_vote_2star', $js2link);

			$js1link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',2)";
			$smarty->assign('link_shakebox_javascript_vote_1star', $js1link);

			$this->votecount = $this->countvotes();
			$smarty->assign('vote_count', $this->votecount);
			
			if($this->votes($current_user->user_id) > 0){
				$smarty->assign('star_class', "-noh");
			} else {
				$smarty->assign('star_class', "");
			}
		}

		if($this->status == "published"){$smarty->assign('category_url', getmyurl("maincategory", $catvar));}
		if($this->status == "queued"){$smarty->assign('category_url', getmyurl("queuedcategory", $catvar));}
		if($this->status == "discard"){$smarty->assign('category_url', getmyurl("discardedcategory", $catvar));}

		$smarty->assign('trackback_url', get_trackback($this->id));
		$smarty->assign('user_logged_in', $current_user->user_login);
		$smarty->assign('randmd5', md5($current_user->user_id.$this->randkey));
		$smarty->assign('user_id', $this->author);
		$smarty->assign('current_user_id', $current_user->user_id);

		if(Enable_Extra_Fields){
			$main_smarty = $smarty; include mnminclude.'extra_fields_smarty.php'; $smarty=$main_smarty;
			$smarty->assign('link_field1', $this->link_field1);
			$smarty->assign('link_field2', $this->link_field2);
			$smarty->assign('link_field3', $this->link_field3);
			$smarty->assign('link_field4', $this->link_field4);
			$smarty->assign('link_field5', $this->link_field5);
			$smarty->assign('link_field6', $this->link_field6);
			$smarty->assign('link_field7', $this->link_field7);
			$smarty->assign('link_field8', $this->link_field8);
			$smarty->assign('link_field9', $this->link_field9);
			$smarty->assign('link_field10', $this->link_field10);
			$smarty->assign('link_field11', $this->link_field11);
			$smarty->assign('link_field12', $this->link_field12);
			$smarty->assign('link_field13', $this->link_field13);
			$smarty->assign('link_field14', $this->link_field14);
			$smarty->assign('link_field15', $this->link_field15);
		}

		$smarty->assign('Enable_Recommend', Enable_Recommend);
		$smarty->assign('Recommend_Type', Recommend_Type);
		$smarty->assign('instpath', my_base_url . my_pligg_base . "/");		
		$smarty->assign('UseAvatars', do_we_use_avatars());
		$smarty->assign('Avatar_ImgSrc', get_avatar('large', "", "", "", $this->userid));
		$smarty->assign('Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $this->userid));
		$owner_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id = ' . $this->id);
		if ($owner_id) {
			$smarty->assign('link_owner_id',$owner_id);
			$smarty->assign('link_owner_url',my_base_url . my_pligg_base . '/user.php?uid=' . $owner_id);
			$owner_nickname = $db->get_var('SELECT user_names FROM ' . table_users . ' WHERE user_id = ' . $owner_id);
			if ($owner_nickname) {
				$smarty->assign('link_owner_nickname',$owner_nickname);
			}
			else {
				$smarty->assign('link_owner_nickname','');
			}
			//get last things
			$limitnum = 3;//show how many things per user in a page
			$lastthingnumsql = "SELECT COUNT(" . table_links . ".link_id) FROM " . table_links . ", " . table_link_owner ." WHERE " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_links .".link_category=2 AND " . table_links . ".link_status != 'discard'" . " AND ". table_link_owner . ".owner_id=" . $owner_id;
			$thingsnum = $db->get_var($lastthingnumsql);
			$last_things_content = '';
			if ($thingsnum > 0) {
				$lastthingsql = "SELECT " . table_links . ".* FROM " . table_links . ", " . table_link_owner ." WHERE " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_links .".link_category=2 AND " .  table_links . ".link_status != 'discard'" . " AND " . table_link_owner . ".owner_id=" . $owner_id . " ORDER BY " . table_links . ".link_date DESC LIMIT 0," . $limitnum;
				$searchsql = mysql_query($lastthingsql);
				$thinglist = array();
				while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($thinglist, $row);
				$last_things_content .= '<table>';
				$user = new User();
				foreach($thinglist as $key => $val){
					$user->id = $thinglist[$key]['link_author'];
					$user->read();
					$last_things_content = $last_things_content . '<tr style="font-size:17px"><td><a href="' . 'story.php?id=' . $thinglist[$key]['link_id'] . '" target="_blank" style="float:left; margin-left:0px; overflow:hidden;">' . $thinglist[$key]['link_title'] . '</a></td><td>' . '共' . $thinglist[$key]['link_votes'] . '人推荐(<a href="user.php?uid='. $user->id .'" target="_blank">' . $user->names .'</a>首推'.')，' . $thinglist[$key]['link_comments'] . '个评论</td></tr>';
				}
				if ($thingsnum > $limitnum) {
					$last_things_content = $last_things_content . "<tr><td><a href='user.php?uid=" . $owner_id . "&view=staff'>更多...</a></td><td>&nbsp</td></tr>";
				}
				$last_things_content .= '</table>';
			}
			//$last_things_content = $lastthingsql;
			$smarty->assign('last_things_content', $last_things_content);		
		}
		else {
			$smarty->assign('link_owner_id',0);
			$smarty->assign('link_owner_url','');
			$smarty->assign('link_owner_nickname','');
		}
		$smarty->assign('Owner_Avatar_ImgSrc', get_avatar('large', "", "", "", $owner_id));
		$smarty->assign('Owner_Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $owner_id));

		$canIhaveAccess = 0;
		$canIhaveAccess = $canIhaveAccess + checklevel('god');
		$canIhaveAccess = $canIhaveAccess + checklevel('admin');
		if($canIhaveAccess == 1)
			{$smarty->assign('isadmin', 'yes');}

		if($this->check_friends == true){
			// For Friends //
				include_once(mnminclude.'friend.php');
				$friend = new Friend;
				// make sure we're logged in and we didnt submit the link.
				if($current_user->user_id > 0 && $current_user->user_login != $this->username()){
					$friend_md5 = friend_MD5($current_user->user_login, $this->username());
					$smarty->assign('FriendMD5', $friend_md5);
		
					$isfriend = $friend->get_friend_status($this->author);
					if (!$isfriend)	{$friend_text = 'add to';	$friend_url = 'addfriend';}
						else{$friend_text = 'remove from';	$friend_url = 'removefriend';}
		
					$smarty->assign('Friend_Text', $friend_text);				
					$smarty->assign('user_add_remove', getmyurl('user_add_remove', $this->username(), $friend_url));
				}
		
				$smarty->assign('Allow_Friends', Allow_Friends);
				$smarty->assign('Enable_AddTo', Enable_AddTo);
			// --- //
		}
		
		if($this->check_saved == true){
			global $cached_saved_links;
			if(isset($cached_saved_links[$this->id])){
				$smarty->assign('link_mine', $cached_saved_links[$this->id]);
			} else {
				$smarty->assign('link_mine', $db->get_row("SELECT * FROM " . table_saved_links . " WHERE saved_user_id=$current_user->user_id AND saved_link_id=$this->id LIMIT 1;"));
			}
		}

		$smarty->assign('user_url_saved', getmyurl('user2', $current_user->user_login, 'saved'));
		$smarty->assign('user_url_add_links', getmyurl('user_add_links', $this->id));
		$smarty->assign('user_url_remove_links', getmyurl('user_remove_links', $this->id));
		$smarty->assign('enable_tags', Enable_Tags);
		$smarty->assign('link_shakebox_index', $link_index);
		$smarty->assign('link_shakebox_votes', $this->votes);
		
		$this->get_current_user_votes($current_user->user_id);
		
		$smarty->assign('link_shakebox_currentuser_votes', $this->current_user_votes);
		$smarty->assign('link_shakebox_currentuser_reports', $this->current_user_reports);

		if($this->reports == -1){
			// reporting was added to the svn and some people started using it
			// so in upgrade if someone already has the reports field, we set it to
			// -1. Then when we read() we check if -1. if it still is, update the count
			// from the votes table and store it into the link_reports field so we
			// don't have to look at the votes table again.
		
			$this->reports = $this->count_all_votes("<0");
			$this->store_basic();
			$smarty->assign('link_shakebox_reports', $this->reports);
		}

		$jslink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$jsreportlink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',-10)";
		$smarty->assign('link_shakebox_javascript_vote', $jslink);

		$jsunvote = "unvote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$smarty->assign('link_shakebox_javascript_unvote', $jsunvote);
		
		$smarty->assign('link_shakebox_javascript_report', $jsreportlink);
		if(!defined('alltagtext')){
			// for pages like index, this ->display was being called for each story
			// which was sometimes 15+ times per page. this way it's just called once
			$smarty->display('blank.tpl'); //this is just to load the lang file so we can pull from it in php
			define('alltagtext', $smarty->get_config_vars('PLIGG_Visual_Tags_All_Tags')); 			
		}
		$alltagtext = alltagtext;
	
		if(Enable_Tags){
			$smarty->assign('tags', $this->tags);
			if (!empty($this->tags)) {
				$tags_words = str_replace(",", ", ", $this->tags);
				$tags_count = substr_count($tags_words, ',');
				if ($tags_count > 1){$tags_words = $tags_words;}

				$tag_array = explode(",", $tags_words);
				$c = count($tag_array);
				$tag_array[$c] = $this->tags;
 				$c++;
 				for($i=0; $i<=$c; $i++)
 				{
 					if(isset($tag_array[$i])){
						if ( $URLMethod == 1 ) { 
						    $tags_url_array[$i] = my_pligg_base . "/search.php?search=".urlencode(trim($tag_array[$i]))."&amp;tag=true";
						} elseif ( $URLMethod == 2) {
						    $tags_url_array[$i] = my_pligg_base . "/tag/" . urlencode(trim($tag_array[$i]));
				    }
				  }
 				}
 				$tag_array[$c - 1] = $alltagtext;

				$smarty->assign('tag_array', $tag_array);
				$smarty->assign('tags_url_array', $tags_url_array);

				$tags_url = urlencode($this->tags);
				$smarty->assign('tags_count', $tags_count);
				$smarty->assign('tags_words', $tags_words);
				$smarty->assign('tags_url', $tags_url);
			}
		}
		
		$smarty->assign('pagename', pagename);
		$smarty->assign('doing', doing);
		$smarty->assign('my_base_url', my_base_url);
		$smarty->assign('my_pligg_base', my_pligg_base);
		$smarty->assign('Default_Gravatar_Large', Default_Gravatar_Large);
			
		$link_index++;
		$vars = '';
		check_actions('lib_link_summary_fill_smarty', $vars);

		return $smarty;
	}

	function print_summary_view_apply($type='full', $fetch = false) {
		global $current_user, $globals, $the_template, $smarty;

		include_once('./Smarty.class.php');
		
		$main_smarty = new Smarty;
		$main_smarty->compile_check=false;
		// enable caching at your own risk. this code is still experimental
		//$smarty->cache = true;
		$main_smarty->cache_lifetime = 120;
		$main_smarty->cache_dir = "templates_c/";
		$main_smarty->compile_dir = "templates_c/";
		$main_smarty->template_dir = "templates/";
		$main_smarty->config_dir = "";
		$main_smarty->assign('pligg_language', pligg_language);
		$main_smarty->config_load("/languages/lang_" . pligg_language . ".conf");

		if(phpnum() == 4) {
			$main_smarty->force_compile = true;
		}

		$main_smarty = $this->fill_smarty_view_apply($main_smarty, $type);

		$main_smarty->assign('use_title_as_link', use_title_as_link);
		$main_smarty->assign('open_in_new_window', open_in_new_window);
		$main_smarty->assign('use_thumbnails', use_thumbnails);
		$main_smarty->assign('the_template', The_Template);

		include mnminclude.'extra_fields_smarty.php';
		if($fetch == false){
			$main_smarty->display($the_template . '/link_summary_view_apply.tpl', 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
		} else {
			return $main_smarty->fetch($the_template . '/link_summary_view_apply.tpl', 'story' . $this->id . "|" . $current_user->user_id . "|" . $type);
		}
	}

	function fill_smarty_view_apply($smarty, $type='full'){

		static $link_index=10;
		global $current_user, $globals, $the_template, $db;

		$smarty->assign('link_id', $this->id);

		if(!$this->read) return $smarty;

		$title_short = htmlspecialchars(utf8_wordwrap($this->title, 30, " ", 1));

		$smarty->assign('viewtype', $type);

		$smarty->assign('story_comment_count', $this->comments());
		
		if($this->get_author_info == true){
			$smarty->assign('link_submitter_id', $this->author);
			$smarty->assign('link_submitter', $this->username());
			$smarty->assign('link_submitter_names', $this->usernames());
			$smarty->assign('submitter_profile_url', getmyurl('user', $this->username()));
		}
		
		//$smarty->assign('link_submit_time', $this->date);
		$smarty->assign('link_submit_time', get_date($this->date));
		$smarty->assign('link_submit_timeago', txt_time_diff($this->date));
		$smarty->assign('link_published_time', $this->published_date);
		$smarty->assign('link_published_date', get_date($this->published_date));
		$smarty->assign('link_published_timeago', txt_time_diff($this->published_date));
		$smarty->assign('link_category', $this->category_name());
		//assign category id to smarty, so we can use it in the templates. Needed for category colors!
		$smarty->assign('category_id', $this->category);

		global $URLMethod;

		{$catvar = $this->category_safe_name();}

		$smarty->assign('Voting_Method', Voting_Method);
		
		if($this->status == "published"){$smarty->assign('category_url', getmyurl("maincategory", $catvar));}
		if($this->status == "queued"){$smarty->assign('category_url', getmyurl("queuedcategory", $catvar));}
		if($this->status == "discard"){$smarty->assign('category_url', getmyurl("discardedcategory", $catvar));}

		$smarty->assign('trackback_url', get_trackback($this->id));
		$smarty->assign('user_logged_in', $current_user->user_login);
		$smarty->assign('randmd5', md5($current_user->user_id.$this->randkey));
		$smarty->assign('user_id', $this->author);
		$smarty->assign('current_user_id', $current_user->user_id);

		$smarty->assign('Enable_Recommend', Enable_Recommend);
		$smarty->assign('Recommend_Type', Recommend_Type);
		$smarty->assign('instpath', my_base_url . my_pligg_base . "/");		
		$smarty->assign('UseAvatars', do_we_use_avatars());
		$smarty->assign('Avatar_ImgSrc', get_avatar('large', "", "", "", $this->userid));
		$smarty->assign('Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $this->userid));
		$owner_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id = ' . $this->id);
		if ($owner_id) {
			$smarty->assign('link_owner_id',$owner_id);
			$smarty->assign('link_owner_url',my_base_url . my_pligg_base . '/user.php?uid=' . $owner_id);
			$owner_nickname = $db->get_var('SELECT user_names FROM ' . table_users . ' WHERE user_id = ' . $owner_id);
			if ($owner_nickname) {
				$smarty->assign('link_owner_nickname',$owner_nickname);
			}
			else {
				$smarty->assign('link_owner_nickname','');
			}	
		}
		else {
			$smarty->assign('link_owner_id',0);
			$smarty->assign('link_owner_url','');
			$smarty->assign('link_owner_nickname','');
		}
		$smarty->assign('Owner_Avatar_ImgSrc', get_avatar('large', "", "", "", $owner_id));
		$smarty->assign('Owner_Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $owner_id));
		
		$canIhaveAccess = 0;
		$canIhaveAccess = $canIhaveAccess + checklevel('god');
		$canIhaveAccess = $canIhaveAccess + checklevel('admin');
		if($canIhaveAccess == 1)
			{$smarty->assign('isadmin', 'yes');}

		$smarty->assign('enable_tags', Enable_Tags);
		$smarty->assign('link_shakebox_index', $link_index);
		$smarty->assign('link_shakebox_votes', $this->votes);
		
		$this->get_current_user_votes($current_user->user_id);
		
		$smarty->assign('link_shakebox_currentuser_votes', $this->current_user_votes);
		
		$jslink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$jsreportlink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',-10)";
		$smarty->assign('link_shakebox_javascript_vote', $jslink);

		$jsunvote = "unvote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$smarty->assign('link_shakebox_javascript_unvote', $jsunvote);
		
		$smarty->assign('link_shakebox_javascript_report', $jsreportlink);
		if(!defined('alltagtext')){
			// for pages like index, this ->display was being called for each story
			// which was sometimes 15+ times per page. this way it's just called once
			$smarty->display('blank.tpl'); //this is just to load the lang file so we can pull from it in php
			define('alltagtext', $smarty->get_config_vars('PLIGG_Visual_Tags_All_Tags')); 			
		}
		$alltagtext = alltagtext;
	
		if(Enable_Tags){
			$smarty->assign('tags', $this->tags);
			if (!empty($this->tags)) {
				$tags_words = str_replace(",", ", ", $this->tags);
				$tags_count = substr_count($tags_words, ',');
				if ($tags_count > 1){$tags_words = $tags_words;}

				$tag_array = explode(",", $tags_words);
				$c = count($tag_array);
				$tag_array[$c] = $this->tags;
 				$c++;
 				for($i=0; $i<=$c; $i++)
 				{
 					if(isset($tag_array[$i])){
						if ( $URLMethod == 1 ) { 
						    $tags_url_array[$i] = my_pligg_base . "/search.php?search=".urlencode(trim($tag_array[$i]))."&amp;tag=true";
						} elseif ( $URLMethod == 2) {
						    $tags_url_array[$i] = my_pligg_base . "/tag/" . urlencode(trim($tag_array[$i]));
				    }
				  }
 				}
 				$tag_array[$c - 1] = $alltagtext;

				$smarty->assign('tag_array', $tag_array);
				$smarty->assign('tags_url_array', $tags_url_array);

				$tags_url = urlencode($this->tags);
				$smarty->assign('tags_count', $tags_count);
				$smarty->assign('tags_words', $tags_words);
				$smarty->assign('tags_url', $tags_url);
			}
		}
		
		$smarty->assign('pagename', pagename);
		$smarty->assign('doing', doing);
		$smarty->assign('my_base_url', my_base_url);
		$smarty->assign('my_pligg_base', my_pligg_base);
		$smarty->assign('Default_Gravatar_Large', Default_Gravatar_Large);
			
		$link_index++;
		$vars = '';
		check_actions('lib_link_summary_fill_smarty', $vars);

		return $smarty;
	}
	
	function truncate_content(){
		if(strlen($this->content) > StorySummary_ContentTruncate){ return substr($this->content, 0, StorySummary_ContentTruncate) . "...";}
		return $this->content;
	}

	function print_shake_box($smarty) {
		global $current_user;
	}

	function rating($linkid)
	{
		require_once(mnminclude.'votes.php');

		$vote = new Vote;
		$vote->type='links';
		$vote->link=$linkid;
		return $vote->rating();
	}

	function countvotes() {
		require_once(mnminclude.'votes.php');

		$vote = new Vote;
		$vote->type='links';
		$vote->link=$this->id;
		return $vote->anycount();
	}

	function count_all_votes($value="> 0") {
		require_once(mnminclude.'votes.php');

		$vote = new Vote;
		$vote->type='links';
		$vote->link=$this->id;
		return $vote->count_all($value);
	}

	function votes($user) {
		require_once(mnminclude.'votes.php');

		$vote = new Vote;
		$vote->type='links';
		$vote->user=$user;
		$vote->link=$this->id;
		return $vote->count();
	}

	function reports($user) {
		require_once(mnminclude.'votes.php');

		$vote = new Vote;
		$vote->type='links';
		$vote->user=$user;
		$vote->link=$this->id;
		return $vote->reports();
	}

	function get_current_user_votes($user) {
		require_once(mnminclude.'votes.php');
		
		$vote = new Vote;
		$vote->type='links';
		$vote->user=$user;
		$vote->link=$this->id;
		$results = $vote->user_list_all_votes();
		
		$votes = 0;
		$reports = 0;
		
		if(is_array($results)){
			foreach ($results as $row){
				if(isset($row->vote_value)){
				if($row->vote_value > 0){$votes = $votes + 1;}
				if($row->vote_value < 0){$reports = $reports + 1;}
			}
		}
		}
				
		$this->current_user_votes = $votes;
		$this->current_user_reports = $reports;
		
	}

	function remove_vote($user=0, $value=10) {
	
		$vote = new Vote;
		$vote->type='links';
		$vote->user=$user;
		$vote->link=$this->id;
		$vote->value=$value;
		$vote->remove();

			$vote = new Vote;
			$vote->type='links';
			$vote->link=$this->id;
			if(Voting_Method == 1){
				$this->votes=$vote->count();
				$this->reports = $this->count_all_votes("<0");
			}
			if(Voting_Method == 2){
				$this->votes=$vote->rating();
				$this->votecount=$vote->count();
				$this->reports = $this->count_all_votes("<0");
			}
			$this->store_basic();

	}
	
	function insert_vote($user=0, $value=10, $group=0) {
		global $anon_karma;
		require_once(mnminclude.'votes.php');
		if($value>10){$value=10;}
		$vote = new Vote;
		$vote->type='links';
		$vote->user=$user;
		$vote->link=$this->id;
		$vote->value=$value;
		$vote->group=$group;
		if($value<10) {$vote->value=($anon_karma/10)*$value;}
		if($user>0) {
			require_once(mnminclude.'user.php');
			$dbuser = new User($user);
			if($dbuser->id>0) {
				if($value<10) {$vote->value = ($dbuser->karma/10)*$value;}
			}
		} else if (!anonymous_vote)
			return;
		if($vote->insert()) {
			if ($group > 0) {
				//add this link to the group
				$this->addtogroup($group);
				$this->updategroupvotes($group);
			}
			$vote = new Vote;
			$vote->type='links';
			$vote->link=$this->id;
			if(Voting_Method == 1){
				$this->votes=$vote->count();
				$this->reports = $this->count_all_votes("<0");
			}
			if(Voting_Method == 2){
				$this->votes=$vote->rating();
				$this->votecount=$vote->count();
				$this->reports = $this->count_all_votes("<0");
			}
			$this->store_basic();
			$this->check_should_publish();
			return true;
		}
		return false;
	}

	function check_should_publish(){
	
		if(Voting_Method == 1){
			// check to see if we should change the status to publish
			if($this->status == 'queued' && $this->votes>=votes_to_publish) {
				$now = time();
				$diff=$now-$this->date;
				$days=intval($diff/86400);
				if ($days <=days_to_publish) {
					$this->publish();
				}
			}
		}
	
		if(Voting_Method == 2){
			if($this->status == 'queued' && $this->votes>=(rating_to_publish * 2) && $this->votecount>=votes_to_publish) {
				$now = time();
				$diff=$now-$this->date;
				$days=intval($diff/86400);
				if ($days <=days_to_publish+1000) {
					$this->publish();
				}
			}
		}
	}

	function category_name() {
		// $the_cats is set in /libs/smartyvariables.php

		global $dblang, $the_cats;

		foreach($the_cats as $cat){
			if($cat->category_id == $this->category && $cat->category_lang == $dblang)
			{ 
				$x = $cat->category_name; 
			}
		}

		return $x;
	}

	function category_safe_name() {
		// $the_cats is set in /libs/smartyvariables.php

		global $dblang, $the_cats;

		foreach($the_cats as $cat){
			if($cat->category_id == $this->category && $cat->category_lang == $dblang)
			{ 
				return $cat->category_safe_name; 
			}
		}
	}
	
	function publish() {
		if(!$this->read) $this->read_basic();
		$this->published_date = time();

		totals_adjust_count($this->status, -1);
		totals_adjust_count('published', 1);

		$this->status = 'published';
		$this->store_basic();
	}

	function username() {
		global $db;
		include_once(mnminclude.'user.php');

		$user = new User;
		$user->id = $this->author;
		$user->read('short');
	  
		$this->username = $user->username;
	    
		return $user->username;
	}

	function usernames() {
		global $db;
		include_once(mnminclude.'user.php');

		$user = new User;
		$user->id = $this->author;
		$user->read('short');
	  
		$this->usernames = $user->names;
	    
		return $user->names;
	}

	function recalc_comments(){
		global $db;
		
		$this->comments = $db->get_var("SELECT count(*) FROM " . table_comments . " WHERE comment_link_id = $this->id");
	}

	function comments() {
		global $db;
		if(summarize_mysql == 1){		
			return $this->comments;
		}else{
		return $db->get_var("SELECT count(*) FROM " . table_comments . " WHERE comment_link_id = $this->id");
		}
	}

	function evaluate_formulas ()
	{
		global $db;
		
		$res = $db->get_results("select * from " . table_formulas . " where type = 'report' and enabled = 1;");
		if (!$res) return;
		foreach ($res as $formula) {
			$reports = $this->count_all_votes("< 0");
			$votes = $this->count_all_votes("> 0");

			$from = $this->date;
			$now = time();
			$diff=$now-$from;
			$hours=($diff/3600);
			$hours_since_submit = intval($hours * 100) / 100;

			$evalthis = 'if (' . $formula->formula . '){return "1";}else{return "0";}';
			if(eval($evalthis) == 1){
				totals_adjust_count($this->status, -1);
				totals_adjust_count('discard', 1);

				$this->status = 'discard';
				$this->store_basic();
			} 
		}
		
	}
	
	function return_formula_system_version()
	{
		// 0.1 original
		// 0.2 added hours_since_submit
		
		return 0.2;
	}
	
	function adjust_comment($value)
	{
		$this->recalc_comments();//add this line because sometimes the num of comments get wrong
		//$this->comments = $this->comments + $value;
	}

	function verify_ownership($authorid){
		global $db;
		
		$sql = 'SELECT `link_id` from `' . table_links . '` WHERE `link_id` = ' . $this->id . ' AND `link_author` = ' . $authorid . ' ORDER BY `link_date` DESC LIMIT 1;';
		if($db->get_var($sql)){
			return true;
		} else {
			return false;
		}
	}
	
	function check_spam($text )
	{
		global $MAIN_SPAM_RULESET;
		global $USER_SPAM_RULESET;

		$regex_url   = "/(http:\/\/|https:\/\/|ftp:\/\/|www\.)([^\/\"<\s]*)/im";
		$mk_regex_array = array();
		preg_match_all($regex_url, $text, $mk_regex_array);

		for( $cnt=0; $cnt < count($mk_regex_array[2]); $cnt++ )
			{
			$test_domain = rtrim($mk_regex_array[2][$cnt],"\\");
			if (strlen($test_domain) > 3)
				{
				$domain_to_test = $test_domain . ".multi.surbl.org";
				if( strstr(gethostbyname($domain_to_test),'127.0.0'))
					{ logSpam( "surbl rejected $test_domain");  return true; }
				}
			}
		$retVal = $this->check_spam_rules($MAIN_SPAM_RULESET, strtoupper($text));
		if(!$retVal) { $retVal = $this->check_spam_rules($USER_SPAM_RULESET, strtoupper($text)); }

		return $retVal;
	}

	#####################################
	# check a file of local rules
	# . . the rules are written in a regex format for php
	#     . . or one entry per line eg: bigtimespammer.com on one line
	####################

	function check_spam_rules($ruleFile, $text)
	{
		if(!file_exists( $ruleFile)) { echo $ruleFile . " does not exist\n"; return false; }
		$handle = fopen( $ruleFile, "r");
		while (!feof($handle))
			{
			$buffer = fgets($handle, 4096);
			$splitbuffer = explode("####", $buffer);
			$expression = $splitbuffer[0];
			$explodedSplitBuffer = explode("/", $expression);
			$expression = strtoupper($explodedSplitBuffer[0]);
			if (strlen($expression) > 0)
				{
				if(preg_match("/".trim($expression)."/", $text))
					{ $this->logSpam( "$ruleFile violation: $expression"); return true; }
				}
			}
		fclose($handle);
		return false;
	}

	
	// log date, time, IP address and rule which triggered the spam	
	function logSpam($message)
	{
		global $SPAM_LOG_BOOK;

		$ip = "127.0.0.0";
		if(!empty($_SERVER["REMOTE_ADDR"])) { $ip = $_SERVER["REMOTE_ADDR"]; }
		$date = date('M-d-Y');
		$timestamp = time();

		$message = $date . "\t" . $timestamp . "\t" . $ip . "\t" . $message . "\n";

		$file = fopen( $SPAM_LOG_BOOK, "a");
		fwrite( $file, $message );
		fclose($file);
	}

	function get_comments($fetch = false){
		
		Global $db, $main_smarty, $current_user, $CommentOrder, $link;
		$link = $this;
		//Set comment order to 1 if it's not set in the admin panel
		if(!isset($CommentOrder)){$CommentOrder = 1;}
		If ($CommentOrder == 1){$CommentOrderBy = "comment_votes DESC, comment_date DESC";}
		If ($CommentOrder == 2){$CommentOrderBy = "comment_date DESC";}
		If ($CommentOrder == 3){$CommentOrderBy = "comment_votes DESC, comment_date ASC";}
		If ($CommentOrder == 4){$CommentOrderBy = "comment_date ASC";}
	
		// get all parent comments
		$comments = $db->get_col("SELECT comment_id FROM " . table_comments . " WHERE comment_link_id=$this->id and comment_parent = 0 ORDER BY " . $CommentOrderBy);
		$output = '';
		$uniqid = rand(50,50000);
		if ($comments) {
		$output .= "<a href='javascript:' onclick=switchdiv(" . $uniqid . ")>查看、添加评论</a>";
		}
		else {
			$output .= "<a href='javascript:' onclick=switchdiv(" . $uniqid . ")>添加评论</a>";
		}
		$output .= "<div id='div-". $uniqid ."' style='display:none'>";
		if ($comments) {
			require_once(mnminclude.'comment.php');
			$comment = new Comment;
			foreach($comments as $comment_id) {
				$comment->id=$comment_id;
				$comment->read();
				$output .= $comment->print_summary($link, true);			
		
				// get all child comments
				$comments2 = $db->get_col("SELECT comment_id FROM " . table_comments . " WHERE comment_parent=$comment_id ORDER BY " . $CommentOrderBy);
				if ($comments2) {
					$output .= '<div style="margin-left:40px">';
					require_once(mnminclude.'comment.php');
					$comment2 = new Comment;
					foreach($comments2 as $comment_id) {
						$comment2->id=$comment_id;
						$comment2->read();
						$output .= $comment2->print_summary($link, true);
					}
					$output .= "</div>\n";
				}
		
	 		} 
	 		
	 		$output .= "<a href='javascript:' onclick=switchdiv(" . $uniqid . ")>收起评论</a>";	
		}
		if ($current_user->authenticated) {
			$output .=  '<fieldset><legend>发表评论</legend>';
			$output .=  '<form action="" method="POST" id="thisform">';
			$output .=  '<label></label>';
			$output .=  '<textarea name="comment_content" id="comment" rows="15" cols="70"/></textarea><br />';
		    $output .=  '<br><input type="submit" name="submit" value="发表评论" class="log2" />';
			$output .=  '<input type="hidden" name="process" value="newcomment" />';
			$output .=  '<input type="hidden" name="randkey" value="' . rand(500,500000) .'" />';
			$output .=  '<input type="hidden" name="link_id" value="'.$this->id.'" />';
			$output .=  '<input type="hidden" name="user_id" value="'.$current_user->user_id.'" />';
			$output .=  '</form>';
			$output .=  '</fieldset>';
		}
		if($fetch == false){
			echo $output;
		} else {
			return $output;
		}
	}

	function get_votes($fetch = false) {
		global $db;
		$storyid = $this->id;
		$avatar_size = 'huge';
		$sql = 'SELECT ' . table_votes . '.*, ' . table_users . '.* FROM ' . table_votes . ' INNER JOIN ' . table_users . ' ON ' . table_votes . '.vote_user_id = ' . table_users . '.user_id WHERE (((' . table_votes . '.vote_value)>0) AND ((' . table_votes . '.vote_link_id)='.$storyid.') AND (' . table_votes . '.vote_type= "links")) AND user_level<>"god";';
		$voters = $db->get_results($sql);
		$voters = object_2_array($voters);
		$output = '';
		if ($voters) {
			$uniqid = rand(50,50000);
			$output .= "<a href='javascript:' onclick=switchdiv(" . $uniqid . ")>推荐人列表</a>&nbsp;&nbsp;&nbsp;&nbsp;";
			$output .= "<div id='div-". $uniqid ."' style='display:'>";
			$output .= '<div style="padding:10px 5px; border-bottom:1px solid #ccc;">';
			$output .= '<div class="whovotedwrapper" id="idwhovotedwrapper' . '">';
			$output .= '<ol>';
			foreach($voters as $key => $val){
				$voters[$key]['Avatar_ImgSrc'] = get_avatar($avatar_size, "", $val['user_login'], $val['user_email']);
				$output .= '<li>';	
				$output .= '<img src="'.$voters[$key]['Avatar_ImgSrc'].'" alt="Avatar" align="top" />';
				$output .= '<br><a href = "user.php?login='.$voters[$key]['user_login'].'">'.$voters[$key]['user_names'].'</a>';
				$output .= '</li>';
			}
			$output .= '</ol>';
			$output .= '</div>';
			$output .= '</div>';
			$output .= '</div>';
		}
		return $output;	
	}
	
	function addtogroup($group) {
		global $db;
		$sql = 'SELECT COUNT(*) FROM ' . table_group_link . " WHERE gl_group_id=$group AND gl_link_id=$this->id";
		$alreadydigg = $db->get_var($sql);
		if ($alreadydigg > 0) {
			//do nothing
			return  true;
		}
		else {
			$sql = "INSERT INTO " . table_group_link . " (gl_group_id, gl_link_id, gl_link_votes) VALUES ( $group, $this->id, 0)";
			$db->query("$sql");	
		}
	}
	
	function updategroupvotes($group) {
		global $db;
		$vote = new Vote;
		$vote->type='links';
		$vote->link=$this->id;
		$vote->group=$group;
		$glvotes = $vote->count(">0",$group);
		$sql = "UPDATE " . table_group_link . " SET gl_link_votes=$glvotes WHERE gl_group_id=$group AND gl_link_id=$this->id";
		return $db->query($sql);
	}
	
	function deal_hunt_info($smarty) {
		global $current_user, $globals, $the_template, $db;
		include_once(mnminclude."hunt.php");
		$hunt = new Hunt();
		$hunt->linkid = $this->id;
		$hunt->read();
		$smarty->assign('deadline',get_date($hunt->deadline)); 
		$smarty->assign('private_info',$hunt->private_info); 
		$smarty->assign('default_date',get_date_dmy($hunt->deadline));
		$smarty->assign('total_applies',$db->get_var("SELECT COUNT(apply_user_id) FROM " . table_apply . " WHERE apply_hunt_id=" . $hunt->id ));
		return $smarty;
	}
	
	function deal_ownerhunt_info($smarty) {
		global $current_user, $globals, $the_template, $db;
		$smarty->assign('ownernames', $current_user->user_names);
		return $smarty;
	}
	
	function deal_lastcomment_info($smarty) {
		global $current_user, $globals, $the_template, $db;
		$smarty->assign('lastcomment_userid', $this->lastcomment_userid);
		$smarty->assign('lastcomment_username', $this->lastcomment_username);
		$smarty->assign('lastcomment_usernames', $this->lastcomment_usernames);
		$smarty->assign('lastcomment_id', $this->lastcomment_id);
		$smarty->assign('lastcomment_time', get_date($this->lastcomment_time));
		$smarty->assign('lastcomment_content', $this->lastcomment_content);
		$smarty->assign('lastcomment_useravatar', get_avatar("large",'',$this->lastcomment_username,"",$this->lastcomment_userid));
		$smarty->assign('lastcomment_useravatar_huge', get_avatar("huge",'',$this->lastcomment_username,"",$this->lastcomment_userid));
		$smarty->assign('lastcomment_userprofileurl', my_base_url . my_pligg_base . '/user.php?login=' . $this->lastcomment_username);
		return $smarty;
	}
	
	function deal_link_info($doing='', $userid=0, $smarty, $type='full') {
		if(!$this->read) return $smarty;
		global $current_user, $globals, $the_template, $db;
		global $URLMethod;
		static $link_index=0;
		$smarty->assign('link_shakebox_index', $link_index);
		$smarty->assign('pagename', pagename);
		$smarty->assign('doing', doing);
		$smarty->assign('my_base_url', my_base_url);
		$smarty->assign('my_pligg_base', my_pligg_base);
		$smarty->assign('Default_Gravatar_Large', Default_Gravatar_Large);
		$smarty->assign('link_id', $this->id);
		$smarty->assign('story_comment_count', $this->comments());
		$smarty->assign('story_status', $this->status);
		$smarty->assign('trackback_url', get_trackback($this->id));
		$smarty->assign('randmd5', md5($current_user->user_id.$this->randkey));
		
		$smarty = $this->deal_linktitle_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkbutton_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkcontent_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkuser_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linktime_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkvote_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkcat_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		if(Enable_Extra_Fields) { $smarty = $this->deal_linkextra_info($doing='', $userid=0, $smarty, $type='full', $link_index); }
		$smarty = $this->deal_linkowner_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkfriend_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linksaved_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkreport_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linkunvote_info($doing='', $userid=0, $smarty, $type='full', $link_index);
		$smarty = $this->deal_linktag_info($doing='', $userid=0, $smarty, $type='full', $link_index);
				
		$link_index++;
		$vars = '';
		check_actions('lib_link_summary_fill_smarty', $vars);
		return $smarty;
}
	
	function deal_linkextra_info($doing='', $userid=0, $smarty, $type='full') {
		global $current_user, $globals, $the_template, $db;
		if(Enable_Extra_Fields){
			$main_smarty = $smarty; 
			include_once mnminclude.'extra_fields_smarty.php'; 
			$smarty=$main_smarty;
			$smarty->assign('link_field1', $this->link_field1);
			$smarty->assign('link_field2', $this->link_field2);
			$smarty->assign('link_field3', $this->link_field3);
			$smarty->assign('link_field4', $this->link_field4);
			$smarty->assign('link_field5', $this->link_field5);
			$smarty->assign('link_field6', $this->link_field6);
			$smarty->assign('link_field7', $this->link_field7);
			$smarty->assign('link_field8', $this->link_field8);
			$smarty->assign('link_field9', $this->link_field9);
			$smarty->assign('link_field10', $this->link_field10);
			$smarty->assign('link_field11', $this->link_field11);
			$smarty->assign('link_field12', $this->link_field12);
			$smarty->assign('link_field13', $this->link_field13);
			$smarty->assign('link_field14', $this->link_field14);
			$smarty->assign('link_field15', $this->link_field15);
		}
		return $smarty;
	}
	function deal_linkuser_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		if($this->get_author_info == true){
			$smarty->assign('link_submitter', $this->username());
			$smarty->assign('link_submitter_id', $this->author);
			$smarty->assign('link_submitter_names', $this->usernames());
			$smarty->assign('submitter_profile_url', getmyurl('user', $this->username()));
		}
		$smarty->assign('user_logged_in', $current_user->user_login);
		$smarty->assign('user_id', $this->author);
		$smarty->assign('current_user_id', $current_user->user_id);
		$smarty->assign('UseAvatars', do_we_use_avatars());
		$smarty->assign('Avatar_ImgSrc', get_avatar('large', "", "", "", $this->userid));
		$smarty->assign('Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $this->userid));
		return $smarty;
	}
	
	function deal_linktime_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$smarty->assign('link_submit_time', get_date($this->date));
		$smarty->assign('link_submit_timeago', txt_time_diff($this->date));
		$smarty->assign('link_published_time', $this->published_date);
		$smarty->assign('link_published_date', get_date($this->published_date));
		$smarty->assign('link_published_timeago', txt_time_diff($this->published_date));
		return $smarty;
	}
	
	function deal_linktag_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$smarty->assign('enable_tags', Enable_Tags);
		if(!defined('alltagtext')){
			// for pages like index, this ->display was being called for each story
			// which was sometimes 15+ times per page. this way it's just called once
			$smarty->display('blank.tpl'); //this is just to load the lang file so we can pull from it in php
			define('alltagtext', $smarty->get_config_vars('PLIGG_Visual_Tags_All_Tags')); 			
		}
		$alltagtext = alltagtext;	
		if(Enable_Tags){
			$smarty->assign('tags', $this->tags);
			if (!empty($this->tags)) {
				$tags_words = str_replace(",", ", ", $this->tags);
				$tags_count = substr_count($tags_words, ',');
				if ($tags_count > 1){$tags_words = $tags_words;}
				$tag_array = explode(",", $tags_words);
				$c = count($tag_array);
				$tag_array[$c] = $this->tags;
		 		$c++;
		 		for($i=0; $i<=$c; $i++)
		 		{
		 			if(isset($tag_array[$i])){
						if ( $URLMethod == 1 ) { 
						    $tags_url_array[$i] = my_pligg_base . "/search.php?search=".urlencode(trim($tag_array[$i]))."&amp;tag=true";
						} elseif ( $URLMethod == 2) {
						    $tags_url_array[$i] = my_pligg_base . "/tag/" . urlencode(trim($tag_array[$i]));
				    }
				  }
		 		}
		 		$tag_array[$c - 1] = $alltagtext;
		
				$smarty->assign('tag_array', $tag_array);
				$smarty->assign('tags_url_array', $tags_url_array);
		
				$tags_url = urlencode($this->tags);
				$smarty->assign('tags_count', $tags_count);
				$smarty->assign('tags_words', $tags_words);
				$smarty->assign('tags_url', $tags_url);
			}
		}
		return $smarty;
	}
	function deal_linkcat_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		{$catvar = $this->category_safe_name();}
		if($this->status == "published"){$smarty->assign('category_url', getmyurl("maincategory", $catvar));}
		if($this->status == "queued"){$smarty->assign('category_url', getmyurl("queuedcategory", $catvar));}
		if($this->status == "discard"){$smarty->assign('category_url', getmyurl("discardedcategory", $catvar));}
		$smarty->assign('link_category', $this->category_name());
		$smarty->assign('category_id', $this->category);
		return $smarty;		
	}
	
	function deal_voter_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$voter_id = $userid;
		$voter_date = unixtimestamp($db->get_var("SELECT vote_date FROM " . table_votes . " WHERE vote_link_id=" . $this->id . " AND vote_user_id=" . $userid));
		$smarty->assign('voter_id', $voter_id);
		$smarty->assign('voter_date', get_date($voter_date));
		$voter_comments_count = $db->get_var("SELECT COUNT(*) FROM " . table_comments . " WHERE comment_link_id=" . $this->id . " AND comment_user_id=" . $userid . " ORDER BY comment_date ASC");
		$smarty->assign('voter_comments_count', $voter_comments_count);
		if ($voter_comments_count > 0) {	
			$voter_comments = array();
			$sqlquery = "SELECT * FROM " . table_comments . " WHERE comment_link_id=" . $this->id . " AND comment_user_id=" . $userid;
			$searchsql = mysql_query($sqlquery);
			while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($voter_comments, $row);
			//$voter_comments_count = count($voter_comments);//this doesn't work
			foreach ($voter_comments as $key => $val) {
				$voter_comments[$key]['currentuservote'] = $db->get_var("SELECT COUNT(*) FROM " . table_votes . " WHERE vote_type='comments' AND vote_link_id=" . $voter_comments[$key]['comment_id'] . " AND vote_user_id=" . $current_user->user_id);
				$voter_comments[$key]['comment_content'] = save_text_to_html($voter_comments[$key]['comment_content']);
			}
			$smarty->assign('voter_comments', $voter_comments);
		}
		return $smarty;
	}
	
	function deal_linkvote_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$smarty->assign('Voting_Method', Voting_Method);
			if(Voting_Method == 2){
				$this->rating = $this->rating($this->id)/2;
				$smarty->assign('link_rating', $this->rating);
				$smarty->assign('link_rating_width', $this->rating * 25);
		
				$js5link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',10)";
				$smarty->assign('link_shakebox_javascript_vote_5star', $js5link);
		
				$js4link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',8)";
				$smarty->assign('link_shakebox_javascript_vote_4star', $js4link);
		
				$js3link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',6)";
				$smarty->assign('link_shakebox_javascript_vote_3star', $js3link);
		
				$js2link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',4)";
				$smarty->assign('link_shakebox_javascript_vote_2star', $js2link);
		
				$js1link = "vote($current_user->user_id, $this->id, $link_index, " . "'" . md5($current_user->user_id . $this->randkey) . "',2)";
				$smarty->assign('link_shakebox_javascript_vote_1star', $js1link);
		
				$this->votecount = $this->countvotes();
				$smarty->assign('vote_count', $this->votecount);
					
				if($this->votes($current_user->user_id) > 0){
					$smarty->assign('star_class', "-noh");
				} else {
					$smarty->assign('star_class', "");
				}
		}
		$smarty->assign('link_shakebox_votes', $this->votes);
		$this->get_current_user_votes($current_user->user_id);
		$smarty->assign('link_shakebox_currentuser_votes', $this->current_user_votes);
		$jslink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$smarty->assign('link_shakebox_javascript_vote', $jslink);
		return $smarty;
	}
		
	function deal_linkcontent_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		if($type == "summary"){
			if($this->link_summary == ""){
				$smarty->assign('story_content', $this->truncate_content());
			} else {
				$smarty->assign('story_content', $this->link_summary);
			}
		}
		if($type == "full"){
			$smarty->assign('story_content', $this->content);
		}
		$smarty->assign('story_desc', $this->content);
		return $smarty;
	}
	
	function deal_linksaved_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		if($this->check_saved == true){
			global $cached_saved_links;
			if(isset($cached_saved_links[$this->id])){
				$smarty->assign('link_mine', $cached_saved_links[$this->id]);
			} else {
				$smarty->assign('link_mine', $db->get_row("SELECT * FROM " . table_saved_links . " WHERE saved_user_id=$current_user->user_id AND saved_link_id=$this->id LIMIT 1;"));
			}
		}
		$smarty->assign('user_url_saved', getmyurl('user2', $current_user->user_login, 'saved'));
		return $smarty;
	}
	
	function deal_linkunvote_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$jsunvote = "unvote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',10)";
		$smarty->assign('link_shakebox_javascript_unvote', $jsunvote);
		return $smarty;
}
	
	function deal_linkreport_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		if($this->reports == -1){
					// reporting was added to the svn and some people started using it
					// so in upgrade if someone already has the reports field, we set it to
					// -1. Then when we read() we check if -1. if it still is, update the count
					// from the votes table and store it into the link_reports field so we
					// don't have to look at the votes table again.
			$this->reports = $this->count_all_votes("<0");
			$this->store_basic();
			$smarty->assign('link_shakebox_reports', $this->reports);
		}
		$smarty->assign('link_shakebox_currentuser_reports', $this->current_user_reports);
		$jsreportlink = "vote($current_user->user_id,$this->id,$link_index," . "'" . md5($current_user->user_id.$this->randkey) . "',-10)";
		$smarty->assign('link_shakebox_javascript_report', $jsreportlink);
		return $smarty;
	}
	
	function deal_linkfriend_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		if($this->check_friends == true){
			// For Friends //
			include_once(mnminclude.'friend.php');
			$friend = new Friend;
			// make sure we're logged in and we didnt submit the link.
			if($current_user->user_id > 0 && $current_user->user_login != $this->username()){
				$friend_md5 = friend_MD5($current_user->user_login, $this->username());
				$smarty->assign('FriendMD5', $friend_md5);
				$isfriend = $friend->get_friend_status($this->author);
				if (!$isfriend)	{$friend_text = 'add to';	$friend_url = 'addfriend';}
				else{$friend_text = 'remove from';	$friend_url = 'removefriend';}
				$smarty->assign('Friend_Text', $friend_text);				
				$smarty->assign('user_add_remove', getmyurl('user_add_remove', $this->username(), $friend_url));
			}
			$smarty->assign('Allow_Friends', Allow_Friends);
			$smarty->assign('Enable_AddTo', Enable_AddTo);
		}
		return $smarty;
	}
	function deal_linkowner_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$owner_id = $db->get_var('SELECT owner_id FROM ' . table_link_owner . ' WHERE link_id = ' . $this->id);
		if ($owner_id) {
			$smarty->assign('link_owner_id',$owner_id);
			$smarty->assign('link_owner_url',my_base_url . my_pligg_base . '/user.php?uid=' . $owner_id);
			$owner_nickname = $db->get_var('SELECT user_names FROM ' . table_users . ' WHERE user_id = ' . $owner_id);
			if ($owner_nickname) {
				$smarty->assign('link_owner_nickname',$owner_nickname);
			} else {
				$smarty->assign('link_owner_nickname','');
			}
			//get last things
			$limitnum = 3;//show how many things per user in a page
			$lastthingnumsql = "SELECT COUNT(" . table_links . ".link_id) FROM " . table_links . ", " . table_link_owner ." WHERE " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_links .".link_category=2 AND " . table_links . ".link_status != 'discard'" . " AND ". table_link_owner . ".owner_id=" . $owner_id;
			$thingsnum = $db->get_var($lastthingnumsql);
			$last_things_content = '';
			if ($thingsnum > 0) {
				$lastthingsql = "SELECT " . table_links . ".* FROM " . table_links . ", " . table_link_owner ." WHERE " . table_links . ".link_id=" . table_link_owner . ".link_id AND " . table_links .".link_category=2 AND " .  table_links . ".link_status != 'discard'" . " AND " . table_link_owner . ".owner_id=" . $owner_id . " ORDER BY " . table_links . ".link_date DESC LIMIT 0," . $limitnum;
				$searchsql = mysql_query($lastthingsql);
				$thinglist = array();
				while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($thinglist, $row);
				$last_things_content .= '<table>';
				$user = new User();
				foreach($thinglist as $key => $val){
					$user->id = $thinglist[$key]['link_author'];
					$user->read();
					$last_things_content = $last_things_content . '<tr style="font-size:17px"><td><a href="' . 'story.php?id=' . $thinglist[$key]['link_id'] . '" target="_blank" style="float:left; margin-left:0px; overflow:hidden;">' . $thinglist[$key]['link_title'] . '</a></td><td>' . '共' . $thinglist[$key]['link_votes'] . '人推荐(<a href="user.php?uid='. $user->id .'" target="_blank">' . $user->names .'</a>首推'.')，' . $thinglist[$key]['link_comments'] . '个评论</td></tr>';
				}
				if ($thingsnum > $limitnum) {
					$last_things_content = $last_things_content . "<tr><td><a href='user.php?uid=" . $owner_id . "&view=staff'>更多...</a></td><td>&nbsp</td></tr>";
				}
				$last_things_content .= '</table>';
			}
			//$last_things_content = $lastthingsql;
			$smarty->assign('last_things_content', $last_things_content);		
		}
		else {
			$smarty->assign('link_owner_id',0);
			$smarty->assign('link_owner_url','');
			$smarty->assign('link_owner_nickname','');
		}
		$smarty->assign('Owner_Avatar_ImgSrc', get_avatar('large', "", "", "", $owner_id));
		$smarty->assign('Owner_Avatar_ImgSrc_Huge', get_avatar('huge', "", "", "", $owner_id));
		return $smarty;
	}
				
	function deal_linkbutton_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$smarty->assign('story_edit_url', getmyurl("editlink", $this->id));
		$smarty->assign('story_admin_url', getmyurl("admin_modify", $this->id));
		$smarty->assign('Enable_Recommend', Enable_Recommend);
		$smarty->assign('Recommend_Type', Recommend_Type);
		$smarty->assign('instpath', my_base_url . my_pligg_base . "/");	
		$canIhaveAccess = 0;
		$canIhaveAccess = $canIhaveAccess + checklevel('god');
		$canIhaveAccess = $canIhaveAccess + checklevel('admin');
		if($canIhaveAccess == 1) {$smarty->assign('isadmin', 'yes');}	
		$smarty->assign('user_url_add_links', getmyurl('user_add_links', $this->id));
		$smarty->assign('user_url_remove_links', getmyurl('user_remove_links', $this->id));
		return $smarty;
	}
				
	function deal_linktitle_info($doing='', $userid=0, $smarty, $type='full',$link_index) {
		global $current_user, $globals, $the_template, $db;
		$url = str_replace('&amp;', '&', htmlspecialchars($this->url));
		$url_short = txt_shorter($url);	
		if($this->url == "http://"){
			$url_short = "http://";
		} else {
			$parsed = parse_url($this->url);
			if(isset($parsed['scheme'])){$url_short = $parsed['scheme'] . "://" . $parsed['host'];}
		}
		$title_short = htmlspecialchars(utf8_wordwrap($this->title, 30, " ", 1));
		$smarty->assign('viewtype', $type);
		$smarty->assign('URL_tagcloud', getmyurl("tagcloud"));
		$smarty->assign('No_URL_Name', No_URL_Name);
		if(track_outgoing == true){
			if(track_outgoing_method == "id"){$smarty->assign('url', getmyurl("out", ($this->id)));}
			if(track_outgoing_method == "title"){$smarty->assign('url', getmyurl("outtitle", urlencode($this->title_url)));}
			if(track_outgoing_method == "url"){$smarty->assign('url', getmyurl("outurl", ($url)));}
		} 
		else {
			$smarty->assign('url', ($url));
		}
		$smarty->assign('enc_url', urlencode($url));
		$smarty->assign('url_short', $url_short);
		$smarty->assign('title_short', $title_short);
		$smarty->assign('title_url', urlencode($this->title_url));
		$smarty->assign('enc_title_short', urlencode($title_short));
		if ($this->title_url == ""){
			$smarty->assign('story_url', getmyurl("story", $this->id)); // internal link to the comments page
		} else {
			$smarty->assign('story_url', getmyurl("storyURL", $this->category_safe_name(), urlencode($this->title_url), $this->id)); // internal link to the comments page
		}
		return $smarty;
	}
}
class HTTPRequest
{
   var $_fp;        // HTTP socket
   var $_url;        // full URL
   var $_host;        // HTTP host
   var $_protocol;    // protocol (HTTP/HTTPS)
   var $_uri;        // request URI
   var $_port;        // port

   // scan url
   function _scan_url()
   {
       $req = $this->_url;

       $pos = strpos($req, '://');
       $this->_protocol = strtolower(substr($req, 0, $pos));

       $req = substr($req, $pos+3);
       $pos = strpos($req, '/');
       if($pos === false)
           $pos = strlen($req);
       $host = substr($req, 0, $pos);

       if(strpos($host, ':') !== false)
       {
           list($this->_host, $this->_port) = explode(':', $host);
       }
       else
       {
           $this->_host = $host;
           $this->_port = ($this->_protocol == 'https') ? 443 : 80;
       }

       $this->_uri = substr($req, $pos);
       if($this->_uri == '')
           $this->_uri = '/';
   }

   // constructor
   function HTTPRequest($url)
   {
		$this->_url = $url;
		$this->_scan_url();
   }

   // download URL to string
   function DownloadToString()
   {
       $crlf = "\r\n";

       // generate request
       $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf
           .    'Host: ' . $this->_host . $crlf
           .    $crlf;

	error_reporting(E_ERROR);
	// fetch
	$this->_fp = fsockopen(($this->_protocol == 'https' ? 'tls://' : '') . $this->_host, $this->_port, $errno, $errstr, 20);
	if(!$this->_fp)
		{return("BADURL");}
	fwrite($this->_fp, $req);
       while(is_resource($this->_fp) && $this->_fp && !feof($this->_fp))
           $response .= fread($this->_fp, 1024);
       fclose($this->_fp);

       // split header and body
       $pos = strpos($response, $crlf . $crlf);
       if($pos === false)
           return($response);
       $header = substr($response, 0, $pos);
       $body = substr($response, $pos + 2 * strlen($crlf));

       // parse headers
       $headers = array();
       $lines = explode($crlf, $header);
       foreach($lines as $line)
           if(($pos = strpos($line, ':')) !== false)
               $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));

       // redirection?
       if(isset($headers['location']))
       {
           $http = new HTTPRequest($headers['location']);
           return($http->DownloadToString($http));
       }
       else
       {
           return($body);
       }
   }
}
?>
